堆排序(C++版)

时间:2023-11-28 12:19:14
#include <iostream>

using namespace std;

void HeapAdjust(int* a, int start, int n)
{
int max=start;
int lchild = start*+;
int rchild = start*+;
if(start <= (n-)/){
if(lchild <=n && a[lchild]>a[max]){
max = lchild;
}
if(rchild <=n && a[rchild]>a[max]){
max = rchild;
}
if(max!=start){
swap(a[start], a[max]);
HeapAdjust(a, max, n);
}
}
} void BuildHeap(int* a, int n){ //n: [0,n]
for(int i = (n-)/; i >=;i--){
HeapAdjust(a, i, n);
}
} void HeapSort(int *a,int n)
{
BuildHeap(a,n);
for(int i=n;i>=1;i--)
{
swap(a[],a[i]);
HeapAdjust(a,,i-);
}
} int main(int argc, char *argv[])
{
int a[]={,,,,,,};
BuildHeap(a,);
for(int i=;i<;i++){
cout << a[i] <<endl;
}
cout << "=================" <<endl;
HeapSort(a,);
for(int i=;i<;i++){
cout << a[i] <<endl;
}
return ;
}