码迷,mamicode.com
首页 > 编程语言 > 详细

面试题9:数组堆化、堆的插入、堆的删除、堆排序

时间:2017-05-13 22:09:46      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:rom   iostream   ack   rtt   csdn   its   net   排序   cto   

参考:白话经典算法系列之七 堆与堆排序

 1 #include <iostream>
 2 #include <climits>
 3 #include <vector>
 4 using namespace std;
 5 
 6 namespace heap {
 7 
 8 //insert an element to a heap
 9 void insertToHeap(vector<int>& h, int x) {
10     h.push_back(x);
11     int n = h.size();
12 
13     int i = n - 1;
14     int p = (i - 1) / 2;  //parent
15     int temp = x;
16     while (p >= 0 && i != 0) {
17         if (h[p] <= temp) {
18             break;
19         }
20         h[i] = h[p];
21         i = p;
22         p = (i - 1) / 2;
23     }
24     h[i] = temp;
25 }
26 
27 void minHeapFixdown(vector<int>& h, int i, int n) {
28     int tmp = h[i];
29     int j = 2 * i + 1;
30     while (j < n) {
31         if (j + 1 < n && h[j + 1] < h[j]) {
32             j++;
33         }
34         if (h[j] >= tmp) {
35             break;
36         }
37         h[i] = h[j];
38         i = j;
39         j = 2 * i + 1;
40     }
41     h[i] = tmp;
42 }
43 
44 //delete an element from a heap
45 void deleteFromHeap(vector<int>& h) {
46     if (h.empty())
47         return;
48     if (h.size() == 1) {
49         h.clear();
50         return;
51     }
52     int n = h.size();
53     h[0] = h[n - 1];
54     h.erase(h.end() - 1);
55     minHeapFixdown(h, 0, n);
56 }
57 
58 //make an array Minimum heap
59 void heapArray(vector<int>& h) {
60     int n = h.size();
61     for (int i = n / 2 - 1; i >= 0; i--) {
62         minHeapFixdown(h, i, n);
63     }
64 }
65 
66 void heapSort(vector<int>& h) {
67     int n = h.size();
68     vector<int> tmp = h;
69     for (int i = 0; i < n; i++) {
70         h[i] = tmp[0];
71         deleteFromHeap(tmp);
72     }
73 }
74 
75 void printHeap(vector<int>& testVec) {
76     for (size_t i = 0; i < testVec.size(); i++) {
77         std::cout << testVec[i] << ",";
78     }
79     std::cout << std::endl;
80 }
81 }
82 ;
83 
84 int main() {
85     vector<int> testVec = { 0, 3, 9, 1, 3, 5 };
86     heap::heapArray(testVec);
87     heap::printHeap(testVec);
88 
89     heap::deleteFromHeap(testVec);
90     heap::printHeap(testVec);
91 
92     heap::insertToHeap(testVec, 4);
93     heap::printHeap(testVec);
94 
95     heap::heapSort(testVec);
96     heap::printHeap(testVec);
97 
98     return 0;
99 }

 

面试题9:数组堆化、堆的插入、堆的删除、堆排序

标签:rom   iostream   ack   rtt   csdn   its   net   排序   cto   

原文地址:http://www.cnblogs.com/wxquare/p/6850381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!