堆排序也是一种非常优秀的排序算法,时间复杂度和快速排序一致
主要想法使利用树形结构,将每一个数以层次顺序保存在树中,然后重建此树,使最大的数字置于顶端
这里就是一个竞争的思想,从底层开始,依次让每一个结点与其父节点进行比较,如果子结点比父节点大,则交换两个结点
这样把树的每一层遍历完,形成的树就称为堆(每个父节点都比子结点大)
这时数组的最大元素已然位于数组头部,交换数组的头部与尾部
此时数组的尾部就处理好了,将未处理的的数组成新数组再次重建树,就把第二大的数字放在了数组头
交换数组头尾,循环往复直到数字只剩一个元素未处理,这个元素就是最小元素,得到一个升序序列
int pow(int i, int n) { //这里写了一个计算幂函数的函数,用于处理循环边界
if (n == 0)
return 1;
int temp = i;
for (int j = 1; j < n; j++)
i = i*temp;
return i;
}
template<class T>void Restore(T* tree, int Count) {
int index = 1;
int temp = 1;
while (index <= Count) {
temp++;
index *= 2;
}
temp--; //计算层数
while (temp>1) { //逐层比较使数组顶为最大值
for (index = pow(2,temp-1); index<=Count&&index<=pow(2,temp)-1; index++)
if (tree[index - 1]>tree[index / 2 - 1])
swap(tree[index - 1], tree[index / 2 - 1]);
temp--;
}
}
template<class T>void HeapSort(T* arr, int Count) {
for (int i = Count; i>1; i--) {
Restore(arr, i);
swap(arr[0], arr[i - 1]);
}
}