向上调整(边插入边调整)
#include <bits/stdc++.h>
using namespace std;
int const N = 1000 + 10;
int a[N],n;
void adjustup(int a[N],int p){ //小顶堆
int parent,child;
int tmp = a[p];
for(child=p;child/2>=1;child=parent){
parent = child / 2;
if(a[parent] > tmp) a[child] = a[parent];
else break;
}
a[child] = tmp;
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
adjustup(a,i); //边插入边向上调整
}
return 0;
}
向下调整(实现堆排序)
void adjustdown(int T[N],int p,int n){
int parent,child;
int tmp = T[p];
for(parent=p;2*parent<=n;parent=child){
child = 2 * parent;
if(child != n && T[child] < T[child+1]) child++;
if(T[child] > tmp) T[parent] = T[child];
else break;
}
T[parent] = tmp;
}
void Heap_Sort(int a[N],int n){
for(int i=n/2;i>=1;i--)
adjustdown(a,i,n);
for(int i=n;i>=1;i--){
swap(a[i],a[1]);
adjustdown(a,1,i-1);
}
}