-
StackOverflow 文档
-
algorithm 教程
-
合并排序
-
自下而上的 Java 实现
public class MergeSortBU {
private static Integer[] array = { 4, 3, 1, 8, 9, 15, 20, 2, 5, 6, 30, 70, 60,80,0,9,67,54,51,52,24,54,7 };
public MergeSortBU() {
}
private static void merge(Comparable[] arrayToSort, Comparable[] aux, int lo,int mid, int hi) {
for (int index = 0; index < arrayToSort.length; index++) {
aux[index] = arrayToSort[index];
}
int i = lo;
int j = mid + 1;
for (int k = lo; k <= hi; k++) {
if (i > mid)
arrayToSort[k] = aux[j++];
else if (j > hi)
arrayToSort[k] = aux[i++];
else if (isLess(aux[i], aux[j])) {
arrayToSort[k] = aux[i++];
} else {
arrayToSort[k] = aux[j++];
}
}
}
public static void sort(Comparable[] arrayToSort, Comparable[] aux, int lo, int hi) {
int N = arrayToSort.length;
for (int sz = 1; sz < N; sz = sz + sz) {
for (int low = 0; low < N; low = low + sz + sz) {
System.out.println("Size:"+ sz);
merge(arrayToSort, aux, low, low + sz -1 ,Math.min(low + sz + sz - 1, N - 1));
print(arrayToSort);
}
}
}
public static boolean isLess(Comparable a, Comparable b) {
return a.compareTo(b) <= 0;
}
private static void print(Comparable[] array) {http://stackoverflow.com/documentation/algorithm/5732/merge-sort#
StringBuffer buffer = new StringBuffer();http://stackoverflow.com/documentation/algorithm/5732/merge-sort#
for (Comparable value : array) {
buffer.append(value);
buffer.append(' ');
}
System.out.println(buffer);
}
public static void main(String[] args) {
Comparable[] aux = new Comparable[array.length];
print(array);
MergeSortBU.sort(array, aux, 0, array.length - 1);
}
}