我尝试实现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 :(得分:0)
您可以阅读java.util.Collections.sort(starter);
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]);
}
}