归并排序
如下图:先分割,在合并;
//归并排序
public static void mergesort(int[] arr){
mergeSortInternal(arr,0,arr.length-1);
}
//分割
public static void mergeSortInternal(int[] arr,int low,int high){
if(low >= high){
return;
}
int mid = (low + high)/2;
mergeSortInternal(arr,low,mid);
mergeSortInternal(arr,mid+1,high);
//分割完成,就开始合并
merge(arr,low,high,mid);
}
//合并方法
public static void merge(int[] arr,int low,int high,int mid){
int s1 = low;
int s2 = mid+1;
int[] tmp = new int[high-low+1];//临时存放合并后的数据
//开始合并
int k = 0;//tmp开始下标
while(s1 <= mid && s2 <= high){//俩个段都有数据
if (arr[s1] <= arr[s2]){
tmp[k++] = arr[s1++];
}else{
tmp[k++] = arr[s2++];
}
}
//第一个归并段还有很多数据
while(s1 <= mid){//第一个还有若干个数据
tmp[k++] = arr[s1++];
}
while(s2 <= high){//第二个还有若干个数据
tmp[k++] = arr[s2++];
}
//此时就有序了
for (int i = 0;i < tmp.length;i++){
arr[low+i] = tmp[i];//将临时存放好的数据给人家放回去;
}
}