码迷,mamicode.com
首页 > 编程语言 > 详细

堆排序的一种实现

时间:2014-10-17 15:01:03      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   for   sp   div   问题   log   amp   

 1 void HeapAdjust(int a[],int s,int m)
2 { 3 int temp = a[s]; 4 5 for(int j=2*s;j<=m;j=j*2) 6 { 7 if(j<m && a[j]<a[j+1]) 8 ++j; 9 if(temp>=a[j]) //如果只写大于而不写等于会出现问题, 10 break; 11 else 12 { 13 a[s]=a[j]; 14 s=j; 15 } 16 } 17 18 a[s] = temp; 19 } 20 21 void HeapSort(int a[],int n) 22 { 23 for(int i=n/2-1;i>=0;--i) 24 HeapAdjust(a,i,n-1); 25 for(int i=n-1;i>0;--i) 26 { 27 swap(a[0],a[i]); //将大顶堆的根与最后一个元素相交换 28 29 HeapAdjust(a,0,i-1); 30 } 31 }


HeapAdjust(int a[],int s,int m)实现的功能是一次调整,假设数组中除了a[s]外都满足大顶堆的定义。

HeapSort(int a[],int n)中有两步,第一步是根据原来的数组建立一个符合定义的大顶堆。    然后把大顶堆的第一个元素与最后一个元素想交换,那么势必使得原来的

大顶堆不在符合定义(即从a[0]到a[i-1])已不是大顶堆,要调整。

堆排序的一种实现

标签:style   blog   color   for   sp   div   问题   log   amp   

原文地址:http://www.cnblogs.com/zqsgreenhand/p/4030945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!