归并排序

归并排序

归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为2-路归并。

算法描述

  • 把长度为n的输入序列分成两个长度为n/2的子序列;
  • 对这两个子序列分别采用归并排序;
  • 将两个排序好的子序列合并成一个最终的排序序列。

image

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//归并排序
public int[] mergeSort(int[] a, int low, int high) {
int mid = (low+high) / 2;
if (low < high) {
mergeSort(a, low, mid);
mergeSort(a, mid+1, high);
merge(a, low, mid, high);
}
return a;
}
private 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++];
}
}

while (i<=mid) {
temp[k++] = a[i++];
}

while (j<=high) {
temp[k++] = a[j++];
}

for(int x = 0; x<temp.length; x++) {
a[x+low] = temp[x];
}
}

总结

递归分段,将对应的两段先排序