归并排序是利用递归和分治思想将数据序列划分为越来越小的半子表,再对半子表进行排序,最后利用递归的方法将排好序的半子表合并成为越来越大的有序序列。
代码实现:
public static void merge(int[] array, int p, int q, int r) {
int i, j, k, n1, n2;
n1 = q - p + 1;
n2 = r - q;
int[] L = new int[n1];
int[] R = new int[n2];
for (i = 0, k = p; i < n1; i++, k++) {
L[i] = array[k];
}
for (j = 0, k = q+1; j < n2; j++, k++) {
R[j] = array[k];
}
for (k = p, i = 0, j = 0; i < n1 && j < n2; k++) {
if (L[i] < R[j]) {
array[k] = L[i];
i++;
} else {
array[k] = R[j];
j++;
}
}
if (i < n1) {
for (j = i; j < n1; j++, k++) {
array[k] = L[j];
}
}
if (j < n2) {
for (i = j; i < n2; i++, k++) {
array[k] = R[i];
}
}
}
public static void mergeSort(int[] array, int p, int r) {
if ( p < r){
int q = (p+r)/2;
mergeSort(array, p, q);
mergeSort(array, q+1, r);
merge(array, p, q, r);
}
}