第六章堆排序之“堆排序HEAPSORT”

来源:互联网 发布:网络歌曲2006 编辑:程序博客网 时间:2024/06/06 02:21

(1)先用BuildMaxHeap()建立最大堆

(2)交换a[1]和a[heapSize],把最大的换到最后

(3)堆大小heapSize减1

(4)因为将最后一个元素换到堆顶可能会破坏堆的性质,所以调用MaxHeapIfy()将新的heapSize大小的堆调整最大堆

(5)将(2)~(4)重复heapSize-1次,这里的heapSize是最初的那个heapSize。因为一共有heapSize个元素,要换heapSize-1次,才能将大的都换到后面来,实现从小到             大排序。


#include <stdio.h>#include <string.h>#include <time.h>#define BUFFER_SIZE 10void MaxHeapIfy(int *a,int i,int heapSize){int left=i;int right=i;int tmp;int largest=i;while(i<=heapSize){left=i<<1;//左子索引 right=(i<<1)+1;//(移位运算比算术运算优先级低!)右子索引 largest=i;if(left<=heapSize&&a[i]<a[left]){largest=left;}if(right<=heapSize&&a[largest]<a[right]){largest=right;}if(i!=largest)//不加这个判断可能会产生死循环,一个劲的在i这打转 {tmp=a[i];a[i]=a[largest];a[largest]=tmp;i=largest;//其实消除递归就要看每次递归变化的那个量 }else{break;}}}void BuildMaxHeap(int *a,int heapSize){int i=0;for(i=BUFFER_SIZE/2;i>0;i--){MaxHeapIfy(a,i,heapSize);}}void HeapSort(int *a,int heapSize){int i=0;int tmp=0;BuildMaxHeap(a,heapSize);for(i=heapSize;i>1;i--){tmp=a[1];a[1]=a[heapSize];a[heapSize]=tmp;heapSize--;MaxHeapIfy(a,1,heapSize);}}void Output(int *a,int len){int i=1;for(i=1;i<=len;i++){printf("%d ",a[i]);}printf("\n");}int main(){int i=0;int a[BUFFER_SIZE+1];//第一个位置即a[0]不用,这样计算子节点的索引简单点。 memset(a,0,sizeof(a));srand((unsigned)time(NULL));for(i=1;i<=BUFFER_SIZE;i++){a[i]=rand()%BUFFER_SIZE;}printf("随机生成数组:"); Output(a,BUFFER_SIZE);HeapSort(a,BUFFER_SIZE);printf("排序后的数组:");Output(a,BUFFER_SIZE);system("pause");return 0;}


原创粉丝点击