思路:它的最直观的想法是将两个有序子序列通过从左到右两两元素相互比较的排序的方法,那么如果使两个子序列有序呢,那就再将这两个子序列两两分,一直分下去的话最后就得到长度为1的各个子序列,这时就相当于每个子序列都是有序的了,最后按照之前的最直观的想法两两比较合并。
甩上代码来:
public static void sort(int[] a,int low,int mid,int high){
int[] tmp = new int[high - low+1];
int i =low;
int j =mid+1;
int k = 0;
while(i<=mid && j<=high){
if(a[i] <a[j]){
tmp[k++] = a[i++];
}
else{
tmp[k++] = a[j++];
}
}
// if one of the block is finished
//because there is no while out of this block,so,use while insteadof if
while(i<=mid){
tmp[k++] = a[i++];
}
while(j<=high){
tmp[k++] = a[j++];
}
for (int t = 0;t<tmp.length;t++){
a[low+t] = tmp[t];
}
}
public static void GBsort(int[] a,int low,int high){
// is + not -
int mid = (high+low)/2;
if(low < high){
GBsort(a,low,mid);
GBsort(a,mid+1,high);
sort(a,low,mid,high);
}
}