#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int parent(int i){//此处数组从1开始 a[0]设置为0;
return i/2;
}
int lchild(int i){
return 2*i;
} int rchild(int i){
return 2*i+1;
}
void swap(int &a,int &b)
{a=a+b;
b=a-b; a=a-b;}
void MaxFix(int a[],int i,int len){
int max;
while(1){
max=i;
int l=lchild(i);
int r=rchild(i);
if(l<=len&&a[l]>a[max]){max=l;}
if(r<=len&&a[r]>a[max]){ max=r;cout<<"test:"<<max<<endl;}
if(max!=i){
cout<<"test:"<<max<<endl;
swap(a[max],a[i]);
i=max;
}else{
break;
}}
}
void build(int a[],int len){
int i=len/2;
while(i>0){
MaxFix(a,i,len);i--;
}
}
void heapSort(int a[],int len){
build(a,len);
for(int i=len;i>=2;i--){
swap(a[1],a[i]);
len--;
MaxFix(a,1,len);
}
int main(int argc, char *argv[]) {
int a[]={0,16,4,10,14,7,9,3,2,8,1};//a[0]无意义,便于处理a[];
heapSort(a,10);
//MaxFix(b,1,3);
for(int i=1;i<11;i++){
cout<<a[i]<<" ";
}
return 0;
}
排序系列之二堆排序的非递归算法
最新推荐文章于 2023-06-13 17:07:32 发布