简书 賈小強
转载请注明原创出处,谢谢!
package com.lab1.test2;
public class Merge {
public static void main(String[] args) {
Comparable[] a = { 5, 3, 1, 2, 4 };
sort(a);
show(a);
}
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
private static void sort(Comparable[] a) {
Comparable[] aux = new Comparable[a.length];
sort(a, aux, 0, a.length - 1);
}
private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
if (lo >= hi) {
return;
}
int mid = lo + (hi - lo) / 2;
sort(a, aux, lo, mid);
sort(a, aux, mid + 1, hi);
merge(a, aux, lo, mid, hi);
}
private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
int i = lo;
int j = mid + 1;
for (int k = lo; k <= hi; k++) {
if (i > mid) {
a[k] = aux[j++];
} else if (j > hi) {
a[k] = aux[i++];
} else if (less(aux, i, j)) {
a[k] = aux[i++];
} else {
a[k] = aux[j++];
}
}
}
private static void exch(Comparable[] a, int i, int j) {
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static boolean less(Comparable[] a, int i, int j) {
return a[i].compareTo(a[j]) < 0;
}
}
输出
1 2 3 4 5
Happy learning !!