堆排序的思想基于堆的形式,堆是一个完全二叉树。首先,1.将数组构造为大顶端表示的树结构;然后,2.将树的根和从最后的叶子节点开始的位置依次交换;3.将新的树执行第2步。最后得到一个排序好的数组。
static void
construct_big_heap(int set[], int length, int idx) {
int temp = set[idx];
for (int i = idx * 2 + 1; i < length; i = i * 2 + 1) {
if (i < length - 1 && set[i] < set[i + 1])
i++;
if (temp < set[i]) {
set[idx] = set[i];
idx = i;
}
else
break;
}
set[idx] = temp;
}
void
heap_sort(int set[], int length) {
for (int idx = length / 2 - 1 ; idx >= 0; idx--)
construct_big_heap(set, length, idx);
for (int idx = length - 1; idx > 0; idx--) {
swap(set[0], set[idx]);
construct_big_heap(set, idx, 0);
}
}
堆排序的时间复杂度为O(nlogn)。