堆排序 Heapsort

Prime + Heap 简直神了 时间优化好多,顺便就把Heapsort给撸了一发

具体看图

 

 

 

 

Heapsort利用完全二叉树+大(小)顶锥的结构每次将锥定元素和锥最末尾的元素交换 同时大(小)顶锥元素数 -1,迭代n-1次级OK了

我这里的是按从小到大拍的

 1 //堆排序 时间复杂度为 O(nlogn)
 2 
 3 void Swap(int *a, int i, int j)   //交换a[i] 和 a[j] 的值
 4 {
 5     int temp = a[i];
 6     a[i] = a[j];
 7     a[j] = temp;
 8 }
 9 
10 void Heapadjust(int *a,int s,int n)     //调整父亲节点,使其满足大(小)顶锥结构 s为父亲节点下标
11 {
12     int temp = a[s];
13     
14     for(int i=2*s; i<n; i*=2)
15     {
16         if(i<n && a[i] < a[i+1])
17             i++;
18         if(temp >= a[i])
19             break;
20         a[s] = a[i];
21         s = i;
22     }
23     a[s] = temp;
24 }
25 
26 void Heapsort(int *a, int n)  //对*a 数组排序,从a[1] - a[n] 排序
27 {
28     for(int i=n/2; i>0; i--)
29         Heapadjust(a,i,n);
30     
31     for(int i=n; i>1; i--)
32     {
33         Swap(a,1,i);
34         Heapadjust(a,1,i-1);
35     }
36 }

 

posted on 2016-08-06 13:17  lazzzy  阅读(278)  评论(0编辑  收藏  举报

导航