public class test {
public static void main(String[] args) {
int N = 10;
int[] a = new int[N];
for (int i = 0; i < N; i++) {
a[i] = (int) (Math.random() * 100);
System.out.print(a[i] + "\t");
}
System.out.println();
sort(a, N - 1);
for (int i = 0; i < N; i++) {
System.out.print(a[i] + "\t");
}
}
private static void sort(int[] a, int last) {
for (int i = (last - 1) / 2; i >= 0; i--) {
compareWithChild(a, i, last);
}
if (last > 0) {
swap(a, 0, last);
sort(a, last - 1);
}
}
private static void compareWithChild(int[] a, int i, int last) {
if (2 * i + 2 <= last) {// 如果有右孩子
if (a[2 * i + 1] > a[2 * i + 2]) {// 不确定加等号,是否效率更高
if (a[2 * i + 1] > a[i]) {
swap(a, i, 2 * i + 1);
compareWithChild(a, 2 * i + 1, last);
}
} else {
if (a[2 * i + 2] > a[i]) {
swap(a, i, 2 * i + 2);
compareWithChild(a, 2 * i + 2, last);
}
}
} else if (2 * i + 1 <= last) {// 如果只有左孩子
if (a[2 * i + 1] > a[i]) {
swap(a, i, 2 * i + 1);
compareWithChild(a, 2 * i + 1, last);
}
}
}
private static void swap(int[] a, int m, int n) {
int t = a[m];
a[m] = a[n];
a[n] = t;
}
}