个人觉得重点写出max_heapify和parent_heapify两个函数就可以,这个版本号内存管理的功能显得特别简单:
#include<iostream> #include<stdio.h> using namespace std; class Heap { public: int size, capacity; int *ele; void max_heapify(int i,int heap[],int len){//数组从0開始 int l,r,largest; l=2*i+1; r=2*i+2; if( l<len && heap[l]>heap[i] ) largest=l; else largest=i; if( r<len && heap[r]>heap[largest] ) largest=r; if(largest!=i){ swap( heap[largest],heap[i] ); max_heapify(largest,heap,len); } } void parent_heapify(int i,int heap[],int len){//和parent结点不断交换 int parent = i / 2; while (heap[i] > heap[parent]) { swap(heap[i], heap[parent]); i = parent, parent = i / 2; } } Heap(int capacity, int heap[], int len) { this->capacity = capacity, this->size = len; ele = heap; for(int i = size/2-1 ; i >= 0; i--) max_heapify(i,ele,size); } bool push(int val) { if (size < capacity) { ele[size++] = val; parent_heapify(size - 1, ele, size); return true; } else return false; } void pop() { swap(ele[0], ele[size--]); max_heapify(0, ele, size); } int top() { return ele[0]; } }; int main() { int a[10] = {1,2,3,4,5,6,7}; int len = sizeof(a) / sizeof(a[0]); Heap heap(10, a, 7); heap.pop(); heap.push(10); return 0; }
Above code isn't right in the function parent_heapify: parent = (i-1) / 2;
完整版:
#include<iostream> #include<stdio.h> using namespace std; class Heap { private: int *arr, size, capacity; public: void max_heapify(int heap[], int i, int size) { int l = 2 * i + 1, largest = i; if (l < size && heap[l] > heap[i]) largest = l; int r = 2 * i + 2; if (r < size && heap[r] > heap[largest]) largest = r; if (largest != i) { swap(heap[largest], heap[i]); max_heapify(heap, largest, size); } } void parent_heapify(int heap[], int i, int size) { if (i >= size) return; int parent = (i - 1) / 2; while (i != 0 && heap[i] > heap[parent]) { swap(heap[i], heap[parent]); i = parent, parent = (i - 1) / 2; } } Heap(int heap[], int len, int cap) { if (len> cap) this->capacity = this->size = len; else this->capacity = cap, this->size = len; arr = new int[capacity]; memcpy(arr, heap, len * sizeof(int)); for (int i = len / 2 - 1; i >= 0; --i) max_heapify(arr, i, size); } ~Heap() { delete[] arr; arr = NULL; } void push(int val) { if (size >= capacity) { capacity *= 2; int *tmp = arr; arr= new int[capacity]; memcpy(arr, tmp, sizeof(arr[0]) * size); delete[] tmp; } arr[size++] = val; parent_heapify(arr, size - 1, size); } void pop() { if (size == 0) return; else { swap(arr[0], arr[--size]); max_heapify(arr, 0, size); } } int top() { return size == 0 ? -1 : arr[size - 1]; } }; int main() { int a[] = {0,1,2,3,4,5,6}; Heap heap(a, sizeof(a) / sizeof(a[0]), 10); heap.push(7); heap.push(8); heap.push(9); heap.push(10); heap.pop(); int res = heap.top(); return 0; }