#include<iostream>
using namespace std;
#include<vector>
//堆排序
void AdjustDown(vector<int>& arr, int n, int parent)
{
int child = parent * 2 + 1;
while (child < n)
{
if (child + 1 < n && arr[child + 1] > arr[child])
child++;
if (arr[child] > arr[parent])
{
swap(arr[child], arr[parent]);
parent = child;//将被交换的结点视为新的parent,因为此节点被换走,很大可能这部分的子树已经不符合堆的特性(根大于左右孩子,所以将其视为根,对其子树进行调整,知道叶节点,说明这一支调整完成)
child = parent * 2 + 1;//左孩子
}
else return;
}
}
void HeapSort(vector<int>& arr)
/*/堆排序首先要建堆,建堆就要对每一个子树都进行堆调整,
如果要升序序列就要建大堆,要降序要建小堆,
因为堆排序每次都把堆顶元素和最后一个为排序的元素交换位置,
因为堆顶一定是最大或最小,这样交换让序列有序,
每次交换后还要进行从根结点到交换位置进行堆调整
*/
{
int n = arr.size();
for (int root = (n - 2) / 2; root >= 0; root--)//从第一个非叶子结点开始进行堆调整
{
AdjustDown(arr, n, root);
}
for (auto x : arr)//可以看到建的大堆或小堆
cout << x << " ";
cout << endl;
int end = n - 1;
while (end)//交换到就剩根end=0,也就退出了
{
swap(arr[0], arr[end]);
AdjustDown(arr, end, 0);
end--;
}
}
int main()
{
vector<int> arr = { 1,2,3,4,5,6,7,8,9,10,11,12 };
HeapSort(arr);
for (auto x : arr)
cout << x << " ";
return 0;
}
堆排序所用二叉树为完全二叉树,用数组存储即可,存储效率是很高的,没有空间浪费