import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] data = {2,4,0,7,1,8,3,6};
sort(data, 0, data.length - 1);
for(int i = 0; i < data.length; i++) {
System.out.print(data[i] + " ");
}
}
public static void sort(int[] data, int p, int r) {
if (p < r) {
int q = (p + r) / 2;
sort(data, p, q);
sort(data, q + 1, r);
merge(data, p, q, r);
}
}
private static void merge(int[] data, int p, int q, int r) {
int[] left = Arrays.copyOfRange(data, p, q + 1);
int[] right = Arrays.copyOfRange(data, q + 1, r + 1);
int i = 0;
int j = 0;
int k = 0;
while (k < r - p + 1) {
if (i == left.length) {
data[p + k] = right[j++];
}
else if (j == right.length) {
data[p + k] = left[i++];
}
else if (left[i] < right[j]) {
data[p + k] = left[i++];
}
else {
data[p + k] = right[j++];
}
k++;
}
}
}
一直搞不清楚这个递归是怎么执行的,就加了个临时数组test[ ]单步走了一边,终于弄懂了~~~
// 测试的代码
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] data = {1,3,4,2};
int[] test = new int[data.length];
sort(data, 0, data.length - 1, test);
System.out.print("out:\t");
for(int i = 0; i < data.length; i++) {
System.out.print(data[i] + " ");
}
}
public static void sort(int[] data, int p, int r, int[] test) {
if (p < r) {
int q = (p + r) / 2;
sort(data, p, q, test);
// System.out.print("sort1.\t");
// for(int i = 0; i < test.length; i++) {
// System.out.print(test[i] + " ");
// }
// System.out.println();
sort(data, q + 1, r, test);
// System.out.print("sort2.\t");
// for(int i = 0; i < test.length; i++) {
// System.out.print(test[i] + " ");
// }
// System.out.println();
merge(data, p, q, r, test);
// System.out.print("merge.\t");
// for(int i = 0; i < test.length; i++) {
// System.out.print(test[i] + " ");
// }
// System.out.println();
}
}
private static void merge(int[] data, int p, int q, int r, int[] test) {
int[] left = Arrays.copyOfRange(data, p, q + 1);
int[] right = Arrays.copyOfRange(data, q + 1, r + 1);
int i = 0;
int j = 0;
int k = 0;
while (k < r - p + 1) {
if (i == left.length) {
data[p + k] = right[j++];
test[p + k] = data[p + k];
}
else if (j == right.length) {
data[p + k] = left[i++];
test[p + k] = data[p + k];
}
else if (left[i] < right[j]) {
data[p + k] = left[i++];
test[p + k] = data[p + k];
}
else {
data[p + k] = right[j++];
test[p + k] = data[p + k];
}
k++;
}
}
}
递归的执行顺序如下:
输出如下:
sort1. 0 0 0 0
sort2. 0 0 0 0
merge. 1 3 0 0
sort1. 1 3 0 0
sort1. 1 3 0 0
sort2. 1 3 0 0
merge. 1 3 2 4
sort2. 1 3 2 4
merge. 1 2 3 4
out: 1 2 3 4