Monday 12 September 2011

Merge Sort in Java

Introduction
In this example we are going to sort integer values of an array using merge sort.

In merge sorting algorithm unsorted values are divided into two equal parts iteratively. Then merge both parts and sort it. Then again merge the next part and sort it. Do it iteratively until  the values are not in sorted order. In merge sorting the number of elements must be even. The merge sorting is invented by John von Neumann in 1945 .
The complexity of the merge sorting is in worst-case O(n log n) and in average case O(n log n).
  
Code description:
In merge sort split the array values in halves recursively until each half has only single  element. Merge the two 1/2 values together and sort the values. Do same steps iteratively until the values are not sorted.

Working of merge sort algorithm:
Say we have an array unsorted  A[0],A[1],A[2]................ A[n-1] and A[n] as input. Then the following steps are followed by merge sort algorithm to sort the values of an array.

Step1:Spliting the values of array
Divide the values into two equal 1/2
   A[0],A[1],A[2].........A[n/2-1]   &  A[n/2]....... .................A[n-1], A[n]

Again divide two equal 1/2
A[0] a[1]A[2]..............A[(n/2-1)/2-1] &  A[(n/2-1)/2]............A[n/2-1],
A[n/2].............A[(2n-1)/2-1]  & a[(2n-1)/2].............A[n-1],A[n]
..........................................................................................................................
..........................................................................................................................
........................................................................................................................
A[0] & A[1] & A[2]& A[3],..............................................................A[n-1]& A[n]

Step2:Merge two values  and sort the values

A[0],A[1] & A[2],A[3]&..................................................................&A[n-1],A[n]
If A[1]<A[0],A[]<A[3]........................................................................A[n-1]>A[n]
then
A[1]A[0],A[2]A[3],...............................................................................A[n]A[n-1]
Step3:Merge four values and sort the values
A[2] A[1] A[0] A[3],...................................................................................A[n-1]
..................................................................................................................
..................................................................................................................
.................................................................................................................
Step3:Merge n values and sort the values
A[2]A[6]......................................................................................................A[n-5]

Where n must be even number.

Steps of Merge Sort:

Say unsorted  an array values are:
12,9,4,99,120,1,3,10


The code of the program :
public class mergeSort{
  public static void main(String a[]){
  int i;
  int array[] {12,9,4,99,120,1,3,10};
  System.out.println("\n\n RoseIndia\n\n");
  System.out.println(" Selection Sort\n\n");
  System.out.println("Values Before the sort:\n");
  for(i = 0; i < array.length; i++)
  System.out.printarray[i]+"  ");
  System.out.println();
  mergeSort_srt(array,0, array.length-1);
  System.out.print("Values after the sort:\n");
  for(i = 0; i <array.length; i++)
  System.out.print(array[i]+"  ");
  System.out.println();
  System.out.println("PAUSE");
  }

  public static void mergeSort_srt(int array[],int lo, int n){
  int low = lo;
  int high = n;
  if (low >= high) {
  return;
  }

  int middle = (low + high2;
  mergeSort_srt(array, low, middle);
  mergeSort_srt(array, middle + 1, high);
  int end_low = middle;
  int start_high = middle + 1;
  while ((lo <= end_low&& (start_high <= high)) {
  if (array[low< array[start_high]) {
  low++;
  else {
  int Temp = array[start_high];
  for (int k = start_high- 1; k >= low; k--) {
  array[k+1= array[k];
  }
  array[low= Temp;
  low++;
  end_low++;
  start_high++;
  }
  }
  }  
}
Output of the example:
C:\array\sorting>javac mergeSort.java
C:\array\sorting>java mergeSort
       RoseIndia
       Selection Sort
Values Before the sort:
12  9  4  99  120  1  3  10
Values after the sort:
1  3  4  9  10  12  99  120
PAUSE
C:\array\sorting>_

29 comments:

Anonymous said...

Hi to evеry bοdy, it's my first pay a quick visit of this web site; this weblog includes awesome and truly good data in favor of visitors.

Also visit my web blog :: bucket--truck.com
Feel free to surf my blog post altec bucket trucks for sale online

Anonymous said...

Hi colleaguеs, itѕ wоnderful pοst about eԁucatiоnand completely explained,
keеp it up all the time.

Fеel free to visit my weblog :: how to assemble a big green egg
my page - big green egg review

Anonymous said...

Do уou minԁ іf I quote a couple of yоuг postѕ аs long as I provide creԁit and sοuгcеs bacκ
to your blog? My wеbsite іs in the exact same arеa of inteгest as уouгs and my visitors
would truly benеfіt frοm somе of the informаtion
уou provide here. Please lеt me know if this oκay ωith you.
Many thanks!

Alѕо vіsit my site - pain relief for athletes

Anonymous said...

І'll right away seize your rss as I can not in finding your e-mail subscription link or e-newsletter service. Do you have any? Kindly permit me know so that I could subscribe. Thanks.

Also visit my web site ... http://www.oklahomacityroofpro.com/
my page - roofing contractors oklahoma city

Anonymous said...

It іs in point of fact a gгeat аnd uѕeful piеce of information.
Ӏ am glaԁ that you јust sharеd this helpful info with us.
Ρlеase κеeρ us up
tо ԁatе like this. Τhanks for sharing.


Here is my webpage Dallas Seo Company 1

Anonymous said...

I tenԁ not to leave a bunch of гemarks, howeveг і ԁіd some searсhing anԁ wound up here "Merge Sort in Java".
And I аctually do have 2 questiоns fοr уou
if it's allright. Is it only me or does it give the impression like a few of the remarks come across like coming from brain dead folks? :-P And, if you are writing at additional online sites, I would like to follow anything fresh you have to post. Would you make a list of all of all your community pages like your twitter feed, Facebook page or linkedin profile?

My web page - www.page1rankingdallas.com

Anonymous said...

Wоw, amazing ωeblog format! Hοw
lengthy haνe you beеn running a blog foг?
уοu make blogging glance easy. The whole glance of your sitе is mаgnificent, as well as
the content matеrial!

Here is my wеb page: how to buy and sell cars guide

Anonymous said...

With hаνin so much written content dо you eѵег run into any issueѕ of plagoriѕm or copyright infringеment?
Mу wеbsіte has a lot of completely unique content Ι've either created myself or outsourced but it appears a lot of it is popping it up all over the internet without my authorization. Do you know any techniques to help reduce content from being stolen? I'ԁ definitelу apprеciate it.


My wеb-site; how to buy and sell cars for profit

Anonymous said...

Admiring the time and effort you put into your blog and in
depth information you offer. It's nice to come across a blog every once in a while that isn't the same outdated
rehashed information. Wonderful read! I've saved your site and I'm including your RSS feeds to my Google account.


my webpage Nike Air Maxnike air max 90

Anonymous said...

Hi! Do you know if they make any plugins to assist with Search Engine
Optimization? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success.
If you know of any please share. Cheers!

Feel free to visit my blog - Cheap NFL Jerseys nfl jerseys

Anonymous said...

Hi there, just became aware of your blog through Google, and found that it's truly informative. I'm going to watch out for brussels.

I'll be grateful if you continue this in future. A lot of people will be benefited from your writing. Cheers!

My blog post - www.wonderware.fr

Anonymous said...

I visited various sites except the audio quality for audio songs existing at this web site is really fabulous.


Feel free to surf to my page - Air Max Femmeair jordans 13

Anonymous said...

Pretty portion of content. I just stumbled upon your weblog and in
accession capital to assert that I get actually loved account your weblog
posts. Anyway I will be subscribing in your feeds
or even I fulfillment you access persistently fast.

Also visit my page - air jordanair jordan

Anonymous said...

Great article.

Here is my web-site ... Cheap Jerseys Free Shipping

Anonymous said...

What's up Dear, are you really visiting this website on a regular basis, if so after that you will without doubt obtain pleasant know-how.

my homepage; Air Jordan

Anonymous said...

This is a topic which is close to my heart... Take care!
Exactly where are your contact details though?

Review my web blog; Air jordan Pas Cher

Anonymous said...

I know this web site gives quality dependent posts and extra material, is
there any other web page which gives these kinds
of stuff in quality?

Here is my web-site Abercrombie

Anonymous said...

It's hard to come by experienced people on this topic, however, you sound like you know what you're talking about!
Thanks

Here is my web-site ... http://Www.coarchitecture.Com

Anonymous said...

Hi there, just wanted to tell you, I liked this post.
It was helpful. Keep on posting!

Here is my web site ... Air Max

Anonymous said...

This article presents clear idea in favor of the new visitors of blogging,
that actually how to do blogging.

my web blog: Nike Air Max

Anonymous said...

If you wish for to grow your experience just keep visiting this web site and
be updated with the most recent gossip posted here.



Feel free to visit my web page: Air Max 2013

Anonymous said...

It's actually a great and helpful piece of information. I'm glad that you shared this helpful information with us.
Please stay us informed like this. Thanks for sharing.


Also visit my blog post: Air Max Pas Cher

Anonymous said...

I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire
someone to do it for you? Plz answer back as I'm looking to construct my own blog and would like to know where u got this from. kudos

my web page; Abercrombie and Fitch

Anonymous said...

hi!,I love your writing very so much! percentage we keep in touch more
about your post on AOL? I require a specialist
in this house to solve my problem. May be that is you! Taking a look ahead
to look you.

Have a look at my webpage; Michael Kors

Anonymous said...

First off I want to say terrific blog! I had a quick question
that I'd like to ask if you do not mind. I was interested to find out how you center yourself and clear your thoughts before writing. I have had a hard time clearing my mind in getting my thoughts out there. I do take pleasure in writing but it just seems like the first 10 to 15 minutes are generally wasted just trying to figure out how to begin. Any recommendations or tips? Thank you!

My site - Air Jordan France

Anonymous said...

Incredible points. Solid arguments. Keep up the amazing work.



Also visit my webpage :: Air Jordan France

Anonymous said...

Hi, its fastidious post about media print, we all understand media is a
enormous source of information.

Feel free to surf to my page: Abercrombie and Fitch

Anonymous said...

Hi there! Do you use Twitter? I'd like to follow you if that would be okay. I'm undoubtedly
enjoying your blog and look forward to new updates.


my page - http://www.abercrombieandfitchbe.com

Anonymous said...

You really make it seem so easy with your presentation but I find this matter to be
actually something which I think I would never understand.
It seems too complex and very broad for me. I'm looking forward for your next post, I will try to get the hang of it!

my blog post ... Louis Vuitton Outlet