首页 > 代码库 > 面试题9:数组堆化、堆的插入、堆的删除、堆排序
面试题9:数组堆化、堆的插入、堆的删除、堆排序
参考:白话经典算法系列之七 堆与堆排序
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:数组堆化、堆的插入、堆的删除、堆排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。