堆排序
时间复杂度
最好情况:O(nlog2n)
最坏情况:O(nlog2n)
平均情况:O(nlog2n)
稳定性
稳定性:不稳定
问题: 给你n个无序的像m的整型数,请使用归并排序实现从小到大的顺序。(0 <= n <= 5 * 104,-1 * 105 <= m <= 1 * 105)
public class HeadSort {
public static void sort(int[] a) {
headSort(a, a.length - 1);
}
private static void headSort(int[] a, int high) {
for (int i = (high - 1) >> 1; i > 0; i--) {
adjust(a, i, high);
}
for (int i = high; i > 0; i--) {
int temp = a[0];
a[0] = a[i];
a[i] = temp;
adjust(a, 0, i - 1);
}
}
private static void adjust(int[] a, int curPeak, int high) {
while (true) {
int child = (curPeak << 1) + 1;
if (child > high) {
break;
}
if (child < high && a[child] < a[child + 1]) {
child++;
}
if (a[child] > a[curPeak]) {
int temp = a[curPeak];
a[curPeak] = a[child];
a[child] = temp;
curPeak = child;
} else {
break;
}
}
}
}