Pages

15 June 2012

Merge Sort using Java

Now let's move on to Merge Sort.Its a pretty simple kind of sort.Let's consider an example first.


So lets see how the program goes .


Program For Merge Sort Using Java
/**
 *
 * @author The Cyber Soul
 */

import java.io.*;
class MergeSort {
            void merge(int a[],int low,int mid,int high)throws Exception
            {
                int i=low;
                int j=mid+1;
                int t[]=new int[high-low+1];
                int k=0;

                while(i<=mid&&j<=high)
                    t[k++]=a[i]<a[j]?a[i++]:a[j++];
                while(i<=mid)
                    t[k++]=a[i++];
                while(j<=high)
                    t[k++]=a[j++];

                System.arraycopy(t,0,a,low,t.length);
            }
            void mergeSort(int a[],int low,int high) throws Exception
            {
                int mid;
                if(low<high)
                {
                mid=(low+high)/2;
                mergeSort(a,low,mid);
                mergeSort(a,mid+1,high);
                merge(a,low,mid,high);

                }
            }
            public static void main(String args[])throws Exception
            {
                    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                    System.out.println("***MERGE SORT***");
                    int i,n;
                    System.out.println("How many elements do you want to sort");
                    n=Integer.parseInt(br.readLine());
                    int array[]=new int[n];
                    System.out.println("Enter the values to be sorted");
                    for(i=0;i<n;i++)
                    {
                         array[i]=Integer.parseInt(br.readLine());
                    }
                    System.out.println("Values before the Sort:\n");
                    for(i=0;i<array.length;i++)
                    {
                        System.out.print(array[i]+" ");
                    }
                    System.out.println();
                    MergeSort s=new MergeSort();
                    s.mergeSort(array,0,n-1);
                    System.out.println("Values after the Sort:\n");
                    for(i=0;i<array.length;i++)
                    {
                        System.out.print(array[i]+" ");
                    }
                    System.out.println();
                    System.out.println("***END OF MERGE SORT***");
            }
}



Technorati Delicious Reddit BlinkList Furl Mixx Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

0 comments:

Post a Comment

Please Feel free to Share your view with us ....

Related Posts Plugin for WordPress, Blogger...
Search Engine Submission - AddMe Hypersmash.com Blogarama - The Blog Directory Bloggers - Meet Millions of Bloggers