import java.util.Arrays;
/**
*
* 归并排序的思想是将数组分成两部分,分别进行排序,然后归并起来。
*
* 最好时间O(nlogn);平均时间O(nlogn); 最坏时间O(nlogn); 辅助存储O(n) 稳定; n大时较好
*
*/
public class MergeSort {
public static void main(String[] args) {
int[] a = new int[] {5,3,9,1,0,10,8,7,15,4,5};
System.out.println(Arrays.toString(a));
mergeSort(a,0,a.length-1);
System.out.println(Arrays.toString(a));
}
public static void mergeSort(int[] arr, int low, int high ) {
int middle = (low+high)/2;
if (low<high) {
//处理左边
mergeSort(arr,low,middle);
//处理右边
mergeSort(arr,middle+1,high);
//归并
merge(arr,low,middle,high);
}
}
public static void merge(int[] arr, int low, int middle, int high) {
//用于存储归并后的临时数组
int[] temp = new int[high-low+1];
//记录第一个数组中需要遍历的下标
int i = low;
//记录第二个数组中需要遍历的下标
int j = middle+1;
//用于记录在临时数组中存放的下标
int index = 0;
//遍历两个数组取出小的数字,存放在临时数组中
while(i<=middle && j<=high) {
//第一个数组的数据更小
if (arr[i]<=arr[j]) {
//把小的数据放入临时数组中
temp[index++] = arr[i++];
}else {
temp[index++] = arr[j++];
}
}
//处理右边数组多余的数据
while(j<=high) {
temp[index++]=arr[j++];
}
//处理左边数组多余的数据
while(i<=middle) {
temp[index++]=arr[i++];
}
//把临时数组中的数据重新存入原数组
for (int k = 0; k < temp.length; k++) {
arr[k+low]=temp[k];
}
}
}
参考来源
https://www.bilibili.com/video/av33835237/?p=25