参考浙大陈越姥姥数据结构
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#define maxsize 100
typedef struct hnode* heap;
struct hnode{
int* arr;
int size;
int capacity;
};
heap init_heap() {
heap H = new hnode;
H->size = 0;
H->capacity = maxsize;
H->arr = new int[H->capacity];
H->arr[0] = INT_MAX; // 最大堆,哨兵
return H;
}
int delete_elem(heap H) { // 每次弹出最大元素
if(H->size == 0) {
cout << "Heap is empty :((" << endl;
return -1;
}
int child, parent;
int last_elem = H->arr[H->size--];
int ret = H->arr[1];
int n = H->size;
for(parent=1; parent*2<=n; parent=child) {
child=parent*2;
if(child+1<=n && H->arr[child+1]>H->arr[child])
child++;
if(H->arr[child] < last_elem)
break;
else
H->arr[parent] = H->arr[child];
}
H->arr[parent] = last_elem;
return ret;
}
void adjust(heap H, int i) { // 最大堆
int child, parent;
int last_elem = H->arr[i];
int n = H->size;
for(parent=i; parent*2<=n; parent=child) {
child = parent*2;
if(child+1 <= n && H->arr[child+1] > H->arr[child])
child++;
if(H->arr[child] < last_elem)
break;
else
H->arr[parent] = H->arr[child];
}
H->arr[parent] = last_elem;
}
void build_heap(heap H) {
int n = H->size;
for(int i=n/2; i>0; i--)
adjust(H, i);
}
int main()
{
heap H = init_heap();
vector<int> nums = {8,6,3,2,1,7,5,9,4}; // 要调整为最大堆的数组
for(int i=0; i<nums.size(); i++) {
H->arr[i+1] = nums[i];
H->size++;
}
// O(n)建立heap
build_heap(H);
for(int i=0; i<10; i++) // 9个元素,最后一次应该是-1
cout << delete_elem(H) << endl;
return 0;
}