堆排序

1 // 堆应用之优先级队列
4 #include <iostream>
5 using namespace std;
6 const int INF = 999999;
7
8 /////////////////////////////////////////////////////////
9 ////////////// 以下代码在堆排序中已讲解过 ///////////////
10 void MaxHeapify(int *a, int i, int len)
11 {
12 int lt = 2*i, rt = 2*i+1;
13 int largest;
14 if(lt <= len && a[lt] > a[i])
15 largest = lt;
16 else
17 largest = i;
18 if(rt <= len && a[rt] > a[largest])
19 largest = rt;
20 if(largest != i)
21 {
22 int temp = a[i];
23 a[i] = a[largest];
24 a[largest] = temp;
25 MaxHeapify(a, largest, len);
26 }
27 }
28
29 void BuildMaxHeap(int *a, int size)
30 {
31 for(int i=size/2; i>=1; --i)
32 MaxHeapify(a, i, size);
33 }
34
35 void PrintArray(int data[], int size)
36 {
37 for (int i=1; i<=size; ++i)
38 cout <<data[i]<<" ";
39 cout<< endl << endl;
40 }
41 ////////////////////////////////////////////////////////////
42
43 // 返回具有最大关键字的元素
44 int HeapMaximum(int *a)
45 {
46 return a[1];
47 }
48
49 // 去掉并返回具有最大关键字的元素
50 // 注意:这里每次MaxHeapify的是heapsize
51 int HeapExtractMax(int *a, int &heapsize)
52 {
53 if(heapsize < 1)
54 cout << "Heap Underflow" << endl;
55 int max = a[1];
56 a[1] = a[heapsize];
57 --heapsize;
58 MaxHeapify(a, 1, heapsize);
59 return max;
60 }
61
62 // 将元素a[i]的值增加到key
63 void HeapIncreaseKey(int *a, int i, int key)
64 {
65 if(key < a[i])
66 cout << "New key is smaller than current key" << endl;
67 a[i] = key;
68 while(i > 1 &&a[i/2] < a[i])
69 {
70 int temp = a[i];
71 a[i] = a[i/2];
72 a[i/2] = temp;
73 i /= 2;
74 }
75 }
76
77 // 插入关键字为key的元素
78 void MaxHeapInsert(int *a, int key, int &heapsize)
79 {
80 ++heapsize;
81 a[heapsize] = -INF;
82 HeapIncreaseKey(a, heapsize, key);
83 }
84
85
86
87 int main()
88 {
89 int len, heapsize;
90 int arr[100] = {0, 15, 13, 9, 5, 12, 8, 7, 4, 0, 6, 2, 1};
91 // 区别len 和 heapsize
92 // heapsize是堆的大小,而len是初始数组的总大小。
93 len = heapsize = 12;
94
95 // 首先建堆
96 BuildMaxHeap(arr, len);
97 cout << "建堆后: " << endl;
98 PrintArray(arr, len);
99
100 // 使用HeapMaximum
101 cout << "当前最大的元素是: " << endl;
102 cout << HeapMaximum(arr) << endl << endl;
103
104 // 使用HeapExtractMax
105 cout << "使用HeapExtractMax后: " << endl;
106 HeapExtractMax(arr,heapsize);
107 PrintArray(arr, heapsize);
108
109 // 再次使用HeapExtractMax
110 cout << "再次使用HeapExtractMax后: " << endl;
111 HeapExtractMax(arr,heapsize);
112 PrintArray(arr, heapsize);
113
114 // 使用HeapIncreaseKey
115 cout << "使用HeapIncreaseKey后: " << endl;
116 HeapIncreaseKey(arr, 2, 15);
117 PrintArray(arr, heapsize);
118
119 // 使用MaxHeapInsert
120 cout << "使用MaxHeapInsert后: " << endl;
121 MaxHeapInsert(arr, 28, heapsize);
122 PrintArray(arr, heapsize);
123 }
posted @ 2011-05-09 23:19  左手写诗  阅读(264)  评论(0编辑  收藏  举报