Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML


 
  
 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 

 
Facing Programming Problem?
Ask Questions?, Browse Latest Questions, Question-Answer Guidelines
Java
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

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>_

Download this example.

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Latest Searches:
get character array
Heap Sort in Java
How to transfer Docume
keyevents
OBIEE Fundmentals
map in hibernate
Catching Exception usi
ajax database conectiv
jsf examples
login form using mysql
how to put logout code
myfaces trinidad
uml examples
character to decimal
text file to creating
validation for char le
string array add eleme
timetable
Localization in struts
return type-methods
nested
Byte Stream class
compare two dates in j
command line java
multiple radio buttons
move file
value change listener
Clustering and Load Ba
java structures
command line
struts2 param tag
jdk1.3vsjdk1.4
text editor
<param name
find a replace bytes i
iterator framework
Date Examples java
java date compare exam
Java code for media pl
uml classes
asset management
java program to transp
Accessing database fro
upload
set size of a button
Javascript tutorials
Javascript DHTML Javas
chart in visual basic
HTML form to upload fi
view record by charact
asset management tool
JFreechart Library: Hi
array sorting
Best CVS G
Arrays
Text Editor in java
Nested loops for JAVA
creating session in st
StringTokenizer specif
struts table creation
lucene
Java
calling one jsp p
J2ee application conte
save image to file
session.createquery
<tr:table >
jsp programs
java random numbers
rss in j2me
bpm
weblogicservcer
articles in uml
AdressAction
anchor tag
edit Employee Records
ArrayList
<sql-query>
struts-tags action
Action list
Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.