堆(heap)本质上是一棵完全二叉树。它分为大根堆和小根堆,对于大根堆,越接近顶部的结点权值越大,并且一个结点的权值一定大于等于它所在的子树的所有结点的权值。小根堆类似,结点的权值小于等于子树结点的权值。

用堆可以完成堆排序,过程类似于选择排序,每次将最大的元素移到最后位置然后再维护堆,复杂度为O(nlogn).

基本操作如下:

 1 #include <iostream>
 2 using std::cout;
 3 using std::endl;
 4 using std::swap;
 5 
 6 template <typename Type> class Heap {
 7 private:
 8     Type *data;
 9     int size;
10     void update(int pos, int n) {
11         int lchild = 2 * pos + 1, rchild = 2 * pos + 2;
12         int max_value = pos;
13         if (lchild < n && data[lchild] > data[max_value]) {
14             max_value = lchild;
15         }
16         if (rchild < n && data[rchild] > data[max_value]) {
17             max_value = rchild;
18         }
19         if (max_value != pos) {
20             swap(data[pos], data[max_value]);
21             update(max_value, n);
22         }
23     }
24 public:
25     Heap(int length_input) {
26         data = new Type[length_input];
27         size = 0;
28     }
29     ~Heap() {
30         delete[] data;
31     }
32     void push(Type value) {
33         data[size] = value;
34         int current = size;
35         int father = (current - 1) / 2;
36         while (data[current] > data[father]) {
37             swap(data[current], data[father]);
38             current = father;
39             father = (current - 1) / 2;
40         }
41         size++;
42     }
43     void output() {
44         for (int i = 0; i < size; i++) {
45             cout << data[i] << " ";
46         }
47         cout << endl;
48     }
49     Type top() {
50         return data[0];
51     }
52     void pop() {
53         swap(data[0], data[size - 1]);
54         size--;
55         update(0, size);
56     }
57     // 请在下面实现堆排序方法 heap_sort
58     void heap_sort(){
59         for(int i=size-1;i>=1;i--){
60             swap(data[i],data[0]);
61             update(0,i);
62         }
63     }
64 };
65 int main() {
66     int arr[10] = { 12, 9, 30, 24, 30, 4, 55, 64, 22, 37 };
67     Heap<int> heap(100);
68     for (int i = 0; i < 10; i++) {
69         heap.push(arr[i]);
70     }
71     heap.output();
72     cout << heap.top() << endl;
73     heap.pop();
74     heap.output();
75     heap.heap_sort();
76     heap.output();
77     return 0;
78 }

 

posted @ 2017-07-16 10:17  NoviScl  阅读(151)  评论(0编辑  收藏  举报