您的位置:首页 > 其它

最小堆与堆排序

2007-06-21 15:47 162 查看
1 #ifndef MINHEAP_H
2 #define MINHEAP_H
3
4 const int MAX_HEAP_SIZE = 100;
5
6 template <typename Type> class MinHeap
7 {
8 public:
9 MinHeap();
10 MinHeap(Type arr[], int size);
11 ~MinHeap() { }
12 void traverse();
13 void heapSort();
14 void outputTop();
15
16 private:
17 Type *heap;
18 int len;
19
20 void adjustHeap(int adjustLen);
21 void swap(Type &a, Type &b);
22 };
23
24 template <typename Type>
25 MinHeap<Type>::MinHeap()
26 {
27 heap = new Type[MAX_HEAP_SIZE];
28 len = 0;
29 }
30
31 template <typename Type>
32 MinHeap<Type>::MinHeap(Type arr[], int size)
33 {
34 heap = new Type[MAX_HEAP_SIZE];
35 len = size;
36 for(int i = 0; i < size; i++)
37 heap[i] = arr[i];
38
39 adjustHeap(len);
40 }
41
42
43 template <typename Type>
44 void MinHeap<Type>::adjustHeap(int adjustLen)//heap[0adjustLen-1]
45 {
46 int curPos = adjustLen/2 - 1;
47 int minChildPos;
48
49 for(int i = curPos; i >= 0; i--)
50 {
51 if(2*i + 2 >= len)
52 minChildPos = 2*i+1;
53 else
54 minChildPos = heap[2*i+1] < heap[2*i+2] ? (2*i+1) : (2*i+2);
55
56 if(heap[i] > heap[minChildPos])
57 {
58 swap(heap[i], heap[minChildPos]);
59 }
60
61 }
62
63 }
64
65 template <typename Type>
66 void MinHeap<Type>::traverse()
67 {
68 for(int i = 0; i < len; i++)
69 cout << heap[i] << " ";
70
71 cout << endl;
72 }
73
74 template <typename Type>
75 void MinHeap<Type>::heapSort()
76 {
77 int oLen = len;
78 while(len > 0)
79 {
80 outputTop();
81 adjustHeap(len);
82 }
83
84 cout << endl;
85
86 len = oLen;
87
88
89 }
90
91 template <typename Type>
92 void MinHeap<Type>::outputTop()
93 {
94 cout << heap[0] << " ";
95 swap(heap[0], heap[len - 1]);
96 len--;
97 }
98
99 template <typename Type>
100 void MinHeap<Type>::swap(Type &a, Type &b)
101 {
102 Type temp;
103
104 temp = a;
105 a = b;
106 b = temp;
107 }
108 #endif

main.cpp

1 #include <iostream.h>
2 #include "minHeap.h"
3
4 int main()
5 {
6 int arr[9] = {25, 32, 8, 4, 7, 34, 63, 47, 30};
7
8 MinHeap<int> H(arr, 9);
9 H.traverse();
10
11
12 H.heapSort();
13
14 H.traverse();
15
16
17 return 0;
18 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: