归并排序
public class MegerSort {
public static void main(String[] args) {
int a[] = { 5, 2, 6, 0, 3, 9, 1, 7, 4, 8 };
System.out.println("排序前的数组");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
Megersort(a, 0, 9);
System.out.println();
System.out.println("排序后的数组");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
public static void Megersort(int a[], int low, int high) {
int mid = (low + high) / 2;
if (low < high) {
Megersort(a, low, mid);
Megersort(a, mid + 1, high);
Meger(a, low, mid, high);
}
}
private static void Meger(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 t = 0; t < temp.length; t++) {
a[t + low] = temp[t];
}
}
}