1)本例使用最小堆,downheap函数把frist位置的值放到合适的位置,让堆还是最小堆。
2)刚开始要从最大的有孩子的位置开始执行downheap函数,把整个数组转换为最小堆。
3)排序的方法是:取第一个元素(最小的)和最后一个元素交换,然后再转换少了一个元素的堆为最小堆,其实就是downheap交换上来的最后一个元素。
4)取到最后就是一个递减的数组了,要递增就使用最大堆。
#include <stdio.h>
#define N 9
void createheap(int a[], int frist, int last);
void downheap(int a[], int frist, int last);
void heapsort(int a[], int frist, int last);
void swap(int *x, int *y);
void printarr(int a[], int n);
void createheap(int a[], int frist, int last){
int i;
for(i=(last-1)/2; i>=0; i--)
downheap(a, i, last);
}
void downheap(int a[], int frist, int last){
int i = frist;
int left = i*2+1;
int temp = a[frist];
while(left<=last){
if(left+1<=last && a[left]>a[left+1]) left++;
if(temp<=a[left]) break;
swap(&a[left], &a[i]);
i = left;
left = i*2+1;
}
}
void heapsort(int a[], int frist, int last){
int i;
for(i=last; i>0; i--){
swap(&a[i], &a[0]);
downheap(a, 0, i-1);
printarr(a, i-1);
}
}
void swap(int *x, int *y){
int i = *x;
*x = *y;
*y = i;
}
void printarr(int a[], int n){
int i;
for(i=0; i<n; i++){
printf("%d ", a[i]);
}
printf("\n");
}
int main(void){
int a[N] = {2, 5, 3, 1, 8, 12, 15, 9, 18};
createheap(a, 0, N-1);
printarr(a, N);
heapsort(a, 0, N-1);
printarr(a, N);
return 0;
}