介绍
归并排序(Merge Sort)是建立在归并操作上的一种有效,稳定的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并。其排序的速度仅次于快速排序,时间复杂度O(n log n)。
Java代码实现
/**
* 归并排序
* @author rocky
* @date 2021/9/10 10:34
*/
public class MergeSort {
public static int[] sort(int[] a, int low, int high) {
int mid = (low + high) / 2;
if (low < high) {
// 左边归并排序
sort(a, low, mid);
// 右边归并排序
sort(a, mid + 1, high);
// 合并两个有序数组
merge(a, low, mid, high);
}
return a;
}
public static void merge(int[] a, int low, int mid, int high) {
int[] temp = new int[high - low + 1];
int i = low;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= high) {
// 对比大小,调整顺序
if (a[i] < a[j]) {
temp[k++] = a[i++];
} else {
temp[k++] = a[j++];
}
}
// 右边剩余元素填充进temp中(因为前面已经归并,剩余的元素必会小于右边剩余的元素)
while (i <= mid) {
temp[k++] = a[i++];
}
// 右边剩余元素填充进temp中(因为前面已经归并,剩余的元素必会大于于左边剩余的元素)
while (j <= high) {
temp[k++] = a[j++];
}
// 调整数组顺序
for (int x = 0; x < temp.length; x++) {
a[x + low] = temp[x];
}
}
public static void main(String[] args) {
int[] a = {11, 6, 4, 7, 1, 31};
sort(a, 0, a.length -1);
Arrays.stream(a).forEach(System.out::println);
}
}
// 输出结果
1
4
6
7
11
31