归并排序:核心思想,将有序的俩个数组合并在另外一个临时数组里面,这样就实现了整体的有序,但是具体实现是不用去判断一个数组可以分成多少段有序序列。而是直接递归成俩个一组,将俩个相邻的数排成有序的,然后将俩个相邻的数据合并
比如原序列 9,3,1,2,8,7,6
递归到最深处时序列变成 (3,9),(1,2),(7,8),6
递归到上一层变成 (1,2,3,9),(6,7,8)
在递归变成 (1,2,3,6,7,8,9)
这样就实现了整个序列的有序
上代码
public class MergeSort {
public static void main(String[] args) {
int[] ints = {2,1,4,10,20,30,12,3};
int[] temp = new int[ints.length];
mergeSort(ints,0,ints.length-1,temp);
System.out.println(Arrays.toString(ints));
}
private static void mergeSort(int[] ints, int left, int right, int[] temp) {
if(left>=right)
return;
int middle = (left+right)>>1;
mergeSort(ints,left,middle,temp);
mergeSort(ints,middle+1,right,temp);
merge(ints,left,middle,right,temp);
}
private static void merge(int[] ints, int left, int middle, int right, int[] temp) {
int rl = middle+1;
int i = left;
int third = left;
while (left<=middle&&rl<=right){
if(ints[left]<ints[rl]){
temp[third++] = ints[left++];
}else {
temp[third++] = ints[rl++];
}
}
while (left<=middle){
temp[third++] = ints[left++];
}
while (rl<=right){
temp[third++] = ints[rl++];
}
while (i<=right){
ints[i] = temp[i++];
}
}
}
归并排序的效率在大部分情况下比冒泡,选择,甚至快排都要高。