代码及其注释如下:
注:本代码默认堆树以数组vector的形式存储..
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
void heapinsert(vector<int>& p, int index) {//确定index结点在树中应该在的位置
while (p[index] > p[(index - 1) / 2]) { //儿子比爸爸大
swap(p, index, (index - 1) / 2);//换
index = (index - 1) / 2;//儿子变爸爸
}
}
void heapify(vector<int>&p,int index,int heapsize ) {//heapify也是一种确定位置的方法
int left = 2 * index + 1;//左儿子
while (left < heapsize) {
int largeist;
if (left + 1 < heapsize) {
largeist = p[left] > p[left + 1] ? left : left + 1;
}
else {
largeist = left;//找出左右儿子谁更大
}
largeist =p[largeist] > p[index] ? largeist : index;//挑出来的儿子再与爸爸比一比
if (largeist == index) break;//若是最后最大值为当前节点,直接break
swap(p,largeist,index);
index = largeist;
left = index * 2 + 1;//继续调整堆结构
}
}
void heapsort(vector<int>& p) {
if (p.empty()||p.size()==1) {
return;
}
/**
for (int i =p.size()-1; i>=0; i--) {
heapify(p, i, p.size());
}
**/
for (int i = 0; i < p.size(); i++) {
heapinsert(p, i);//让堆变成大根堆
}
int n =p.size();
swap(p,0,--n);//p[0]就是最大的,把它换到它应该去的位置
while (n > 0) {
heapify(p, 0, n);//用heapify调整堆后根结点就是当前最大的值。
swap(p, 0, --n);
}
}
int main() {
vector<int>p = {1,2,3,4,5,4,8,5,9,10};
heapsort(p);
for (auto i : p) {
cout << i<<" ";
}
return 0;
}