2017-02-11 3 views
0

J'ai essayé d'implémenter le MergeSort, mais il n'affiche pas le bon ordre du numéro. Je veux voir ce qui s'est passé dans mon code et comment le réparer correctement.MergeSort ne fonctionne pas dans mon code

public class MergeSort { 

    private static void sort(int[]a,int start,int end){ 
     if(start>=end){return;} 

     int halfway=(start+end)/2; 
     sort(a,start,halfway); 
     sort(a,halfway+1,end); 
     //now that the halves are sorted 
     int []scratch=new int[end-start+1]; 
     int g1=start,g2=halfway+1;//i is the next inedex in the first half to consider 
     //j is the next index in the second half to consder 
     //k is the next index to populating in the scrach arry 
     for(int p=0;p<=scratch.length;p++){ 


      if(a[g1]<a[g2]){ 
       scratch[p]=a[g1];g1++;//smaller one is a[i] 
       if(g1>=halfway){break;} 

      } 


      else {scratch[p]=a[g2]; 
       g2++; 
       if (g2>=end){break;} 
      } 
      if(g1>halfway+1){ 
       scratch[p]=a[g2]; 
        g2++; 
       } 
      if(g2>end+1){ 
       scratch[p]=a[g1]; 
       g1++; 
      } 
      scratch=a; 


     } 

    } 
    public static void sort(int[]a) 
      { 
     sort(a,0,a.length-1); 

      } 
    public static void main(String[] args){ 
     int[] starter={2,1,3,5,6,7,8}; 
     sort(starter); 
     for(int i=0;i<starter.length;i++){ 
      System.out.print(" "+starter[i]); 
     } 

    } 
} 
//if first stack is empty then you grab the next one, 
//if get1 pass to the stopat1(mid+1),then it need to copy the rest of the number,the rest of number are being sorted 
//It also apply at get2 as well. 

Répondre

0

Vous pouvez lire java.util.Collections.sort (démarreur);

public static <T extends Comparable<? super T>> void sort(List<T> list) { 
    Object[] a = list.toArray(); 
    Arrays.sort(a); 
    ListIterator<T> i = list.listIterator(); 
    for (int j=0; j<a.length; j++) { 
     i.next(); 
     i.set((T)a[j]); 
    } 
} 
+0

Ce n'est pas le but de cette affectation, –