这个堆排序算法,采用的是最大堆;最小堆,通常在构造最小优先队列时使用。
//堆排序 2013/09/29
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <malloc.h>
int heapSize = 0;
void swap(int *a, int *b){
int tmp = *a;
*a = *b;
*b = tmp;
}
int left(int p){
return 2*p+1; //下标从0开始的写法,如果从1开始,左子节点为2*p
}
int right(int p){
return 2*p + 2;
}
int parent(int n){
return (n - 1)/2;
}
void maxHeapify(int *a, int i){
int l,r,largest;
l = left(i);
r = right(i);
if ( l < heapSize && a[l] > a[i]) //不要写成l <= heapSize,会导致排序出错
{
largest = l;
}else{
largest = i;
}
if ( r < heapSize && a[r] > a[largest])
{
largest = r;
}
if (largest != i)
{
swap(&a[largest],&a[i]);
maxHeapify(a,largest);
}
}
void buildMaxHeap(int *a){
int i;
for (i = (heapSize - 1) / 2; i >= 0 ; --i) //关键点,避免了对叶子节点进行maxHeapify操作
{
maxHeapify(a,i);
}
}
void heapSort(int *a){
int i;
for (i = heapSize - 1; i > 0; --i)
{
swap(&a[i],&a[0]);
heapSize--; //千万不要漏了
maxHeapify(a,0);
}
}
int initArr(int** a){
int i,n;
srand(time(NULL));
printf("Input the size of array:");
scanf("%d",&n);
*a = (int *)malloc(n*sizeof(int));
for(i = 0; i < n; i++){
(*a)[i] = rand()%100;
}
return n;
}
void printArr(int* a, int n){
int i;
for (i = 0;i < n; i++){
printf("%d,",a[i]);
}
printf("\n");
}
void main(){
int* arr;
int n;
n = initArr(&arr);
heapSize = n;
printArr(arr,n);
// maxHeapify(arr,0);
buildMaxHeap(arr);
heapSort(arr);
printArr(arr,n);
//printf("%d\n",0/2 );
}