package sort;
//归并排序
public class MergeSort {
public static void main(String[] args) {
MergeSort ms = new MergeSort();
int[] ok = ms.mergesort(new int[] { 11, 8, 3, 9, 7, 1, 2, 5 ,4});
for (int i : ok) {
System.out.println(i);
}
}
private int[] mergesort(int[] arr) {
return mergesort_c(arr, 0, arr.length - 1);
}
private int[] mergesort_c(int[] arr, int b, int e) {
if (e - b == 0) {
// 只有一个值
return new int[] { arr[e] };
}
int p = ((e - b) / 2) + b;
int[] x = mergesort_c(arr, b, p);
int[] y = mergesort_c(arr, p + 1, e);
// 合并函数
return merge(x, y);
}
int[] merge(int[] q, int[] p) {
int[] xy = new int[q.length + p.length];
int qi = 0;
int pi = 0;
for (int i = 0; i < xy.length; i++) {
if (qi == q.length) {
for (int j = i; pi < p.length; j++) {
xy[j] = p[pi];
pi += 1;
}
break;
}
if (pi == p.length) {
for (int j = i; qi < q.length; j++) {
xy[j] = q[qi];
qi += 1;
}
break;
}
if (q[qi] < p[pi]) {
xy[i] = q[qi];
qi += 1;
} else {
xy[i] = p[pi];
pi += 1;
}
}
return xy;
}
}
自己实现了一下归并排序,请大家指点。