int left(int i){
return 2*i+1;
}
int right(int i){
return 2*i+2;
}
void max_heapify(int a[],int length,int max){
int l=left(max);
int r=right(max);
int largest = max;
if(l<=length && a[max] <a[l]){
largest = l;
}else{
largest = max;
}
if(r <=length && a[largest] <a[r]){
largest = r;
}
if(largest != max){
int tmp=a[largest];
a[largest]=a[max];
a[max]=tmp;
max_heapify(a,length,largest);
}
}
void build_max_heap(int a[],int length){
for(int i=length/2;i>=0;i--){
max_heapify(a,length,i);
}
}
void max_heap_sort(int a[],int size){
int length = size-1;
build_max_heap(a,length);
for(int i=length;i >0;i--){
int tmp = a[i];
a[i]=a[0];
a[0] = tmp;
length--;
max_heapify(a,length,0);
}
}
排序之五----堆排序
最新推荐文章于 2022-12-23 14:44:16 发布