归并排序的主要思想是分而治之,将一个大问题分解成小的子问题来解决。是一种十分高效的稳定排序算法,而且,归并排序的最好,最坏,平均时间复杂度均为O(nlogn)
比如[11, 8, 3, 9, 7, 1, 2, 5] 采用递归的方法实现归并排序,递归深度为log2n
/**
* 归并排序
* @param arrays
*/
public void sort(int[] array) {
int[] temp = new int[array.length];
sort(array, 0, array.length-1, temp);
}
public void sort(int[] arr, int left, int right, int[] temp) {
if (left < right) {
int mid = (left + right) / 2;
sort(arr, left, mid, temp);
sort(arr, mid+1, right, temp);
merge(arr, left, mid, right, temp);
}
}
public void merge(int[] arr, int left, int mid, int right, int[] temp) {
// 左序列指针
int i = left;
// 右序列指针
int j = mid + 1;
// 临时数据指针
int t = 0;
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
temp[t++] = arr[i++];
}else {
temp[t++] = arr[j++];
}
}
// 将左边剩余元素填充进temp中
while (i <= mid) {
temp[t++] = arr[i++];
}
// 将右边剩余元素填充进temp中
while (j <= right) {
temp[t++] = arr[j++];
}
t = 0;
// 将temp中的元素全部拷贝到原数组中
while (left <= right) {
arr[left++] = temp[t++];
}
}