2017-02-11 4 views
0

Я попытался реализовать MergeSort, но он не отображает правильный порядок числа. Я хочу посмотреть, что произошло в моем коде и как правильно его исправить.MergeSort не работает в моем коде

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. 

ответ

0

Вы можете прочитать java.util.Collections.sort (стартер);

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

Это не назначение этого задания, –

Смежные вопросы