//建堆时向下调整,或者删除元素进行向下调整
void downAdjust(int root,int n){
int i = root , j = i*2;
while(j<=n){
if(j+1<=n&&heap[j+1]>heap[j]) j++;
if(heap[i]<heap[j]){
swap(heap[i],heap[j]);
i = j;
j = j*2;
}
else break;
}
}
//向上调整,用于插入元素时使用
void upAdjust(int root){
int i = root,j = i/2;
while(j>=1){
if(heap[j]<heap[i]){
swap(heap[i],heap[j]);
i = j;
j = j/2;
}
else break;
}
}
//删除堆顶元素
void deleteTop(int n){
heap[1] = heap[n];
n--;
downAdjust(1,n);
}
//插入元素
void insert(int key,int n){
heap[n] = key;n++;
upAdjust(n);
}
//建堆
void Creat_Heap(int N){
for(int i = N/2;i>=1;i--)
downAdjust(i,N);
}
//堆排序
void heapSort(int n){
for(int i=n;i>=1;i--){
swap(heap[i],heap[1]);
downAdjust(1,i-1);
}
}
完整代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 100;
int heap[maxn];
void downAdjust(int root,int n){
int i = root , j = i*2;
while(j<=n){
if(j+1<=n&&heap[j+1]>heap[j]) j++;
if(heap[i]<heap[j]){
swap(heap[i],heap[j]);
i = j;
j = j*2;
}
else break;
}
}
void upAdjust(int root){
int i = root,j = i/2;
while(j>=1){
if(heap[j]<heap[i]){
swap(heap[i],heap[j]);
i = j;
j = j/2;
}
else break;
}
}
void deleteTop(int n){
heap[1] = heap[n];
n--;
downAdjust(1,n);
}
void insert(int key,int n){
heap[n] = key;n++;
upAdjust(n);
}
void Creat_Heap(int N){
for(int i = N/2;i>=1;i--)
downAdjust(i,N);
}
void heapSort(int n){
for(int i=n;i>=1;i--){
swap(heap[i],heap[1]);
downAdjust(1,i-1);
}
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt","r",stdin);
#endif
int N;scanf("%d",&N);
for(int i=1;i<=N;i++){
scanf("%d",&heap[i]);
}
for(int i=1;i<=N;i++) cout<<heap[i]<<" ";
cout<<endl;
Creat_Heap(N);
heapSort(N);
for(int i=1;i<=N;i++) cout<<heap[i]<<" ";
}
输出结果