归并排序
思想:图解
代码:
public static void sort(int[] a,int low,int high){
if(low <high){
int mid = (low+high)/2;
sort(a,low,mid);
sort(a,mid+1,high);
mergeSort(a,low,mid,high);
}
}
private static void mergeSort(int[] a, int low, int mid, int high) {
int lowStart = low;
int highStart = mid + 1;
int tmp = low;
int m = low;
int[] merge = new int[a.length];
while(lowStart <= mid && highStart <= high){
if(a[lowStart] <= a[highStart]){
merge[tmp++] = a[lowStart++];
}
else{
merge[tmp++] = a[highStart++];
}
}
while(highStart <= high){
merge[tmp++] = a[highStart++];
}
while(lowStart <= mid){
merge[tmp++] = a[lowStart++];
}
//将排好序的数组放到a中
while (m <= high) {
a[m] = merge[m];
//System.out.print(a[m]+" ");
m++;
}
}
***帅气的远远啊***