堆排序 详见大话数据结构p396
1 // 堆排序分为两个步骤: 2 // 第一:将我们现有的序列构造成为大顶堆的形式; 自下而上,从右向左 3 // 第二:正式进行排序; 4 5 //堆排序的时间复杂度为 O(nlogn) 6 7 8 9 void Heapsort(sqlist* L) 10 { 11 int i; 12 for(i = L->length/2;i>0;i--) //进行大顶堆的构造,i=L->length/2 表示自下而上排序最靠后的那个非终端节点的序号
13 HeapAdjust(L,i,L->length);
14 for(i = L->length;i>0;i--) //进行排序
15 {
16 swap(L,1,i);
17 HeapAdjust(L,1,i-1);
18 }
19
20 }
21
22
23 void HeapAdjust(sqlist* L,int s,int m)
24 {
25 int temp,j;
26 temp = L->r[s]; //s是当前的结点
27 for(j = 2*s;j>0;j*=2)
28 {
29 if (j<m && L->r[j]<L->r[j+1])
30 ++j;
31 if (temp >= L->r[j])
32 break;
33 L->r[s] = L->r[j];
34 s = j;
35
36 }
37 L->r[s] = temp;
38 }
39
40
41 void swap(sqlist* L,int i,int j)
42 {
43 temp = L->r[i];
44 L->r[i] = L->r[j];
45 L->r[j] = temp;
46 }
浙公网安备 33010602011771号