今天在公司看stl源码分析,感觉有点无聊。花一个小时写了一个可扩容的Heap,虽然速度很慢,但是写出来的感觉还是很不错的。
#include <iostream> using namespace std; class Heap{ public: Heap(int t_size) { //auto_resize size = t_size; arr = (int *)malloc(sizeof(int) * (t_size) + 1); end = 0; } void resize(int t_size) { int * t_arr = (int *)malloc(sizeof(int) * (t_size) + 1); if (t_size < end) end = t_size; for (int i = 1; i <= end; ++i) { t_arr[i] = arr[i]; } free(arr); arr = t_arr; size = t_size; } void push(int num) { if (end == size) { resize(2 * size); }; end += 1; if (end == 1) { arr[end] = num; } int cur = end; arr[cur] = num; while (cur != 1) { if (arr[cur] > arr[(int)(cur/2)]) { int temp = arr[cur]; arr[cur] = arr[(int)(cur/2)]; arr[(int)(cur/2)] = temp; } cur = cur/2; } } int pop() { if (end == 1) { end = 0; return arr[1]; } int res = arr[1]; int cur = 1; arr[cur] = arr[end]; while (cur <= end) { if (2 * cur + 1 <= end && (arr[cur] < arr[2 * cur] || arr[cur] < arr[2 * cur + 1])) { if (arr[2 * cur] > arr[2 * cur + 1]) { int temp = arr[2 * cur]; arr[2 * cur] = arr[cur]; arr[cur] = temp; cur = 2 * cur; } else { int temp = arr[2 * cur + 1]; arr[2 * cur + 1] = arr[cur]; arr[cur] = temp; cur = 2 * cur + 1; } } else if (2 * cur <= end && arr[cur] < arr[2 * cur]) { int temp = arr[2 * cur]; arr[2 * cur] = arr[cur]; arr[cur] = temp; cur = 2 * cur; } else { break; } } end -= 1; return res; } void print() { while (end) { cout << pop() << " "; } cout << endl; } void _print() { for (int i = 1; i <= size; ++i) { cout << arr[i] << " "; } cout << endl; } private: int * arr; int size; int end; }; int main() { Heap h(10); vector<int> ivect{1, 5 ,3, 2, 6, 8, 2, 3}; for (int i = 0; i < ivect.size(); ++i) { h.push(ivect[i]); } h._print(); for (int i = 0; i < 10; ++i) { h.push(1); } h._print(); h.resize(7); h.print(); h._print(); return 0; }
标签:扩容,arr,end,cur,temp,实现,int,Heap,size From: https://www.cnblogs.com/woodx/p/17106630.html