skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Monday, September 17, 2012

Program to sort the numbers using merge Sort

Posted by Admin at 11:57 AM – 0 comments
 

This program will help us in understanding and developing merge sort


public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Merge obj=new Merge();
  int a[]={34,56,23,55,78,3,88};
  
  Merge.divide(a,0,6);
  for(int i=0;i<a.length;i++)
   System.out.println("---"+a[i]);

 }

}





public class Merge {
 public static void divide(int array[],int low,int high)
 {
  System.out.println("divide method");
  
  if(low<high)
  {
   int mid=(low+high)/2;
   divide(array,mid,low);
   divide(array,mid+1,high);
   Merge.mergeArray(array,low,mid,high);
  }
 }

 public static void mergeArray(int array[],int low,int mid,int high)
 {
  System.out.println("MErger method");
  int tempArray[]=new int[array.length];
  int i=low;
  int j=low;
  int k=mid+1;
  for(int l=0;l<array.length;l++)
  {
   System.out.println(array[l]);
  }
  
  while(j<=mid&&k<=high)
  {
   if(array[j]<=array[k])
   {
    tempArray[i]=array[j];
    i++;
    j++;
   }
   else
   {
    tempArray[i]=array[k];
    k++;
    i++;
   }
   
  }
  for(;j<mid;j++)
  {
   tempArray[i]=array[j];
   i++;
  }
  for(;k<high;k++)
  {
   tempArray[i]=array[k];
   i++;
   k++;
  }
  for(int l=0;l<array.length;l++)
  {
   System.out.println("Sorted"+tempArray[l]);
  }
  for(i=0;i<tempArray.length;i++)
   array[i]=tempArray[i];
  
  
 }

}


Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger