一个优先队列的实现:
#include <iostream>
#define MAXSIZE 100
typedef struct heap {
int size;
int capacity;
int* a;
}Heap;
Heap heap;
void initHeap() {
heap.size = 0;
heap.capacity = MAXSIZE;
heap.a = new int[MAXSIZE];
}
void insert(int data)
{ heap.size += 1;
heap.a[heap.size] = data;
int index = heap.size;
for(; index > 1; index = index / 2) {
if(heap.a[index] < heap.a[index/2]) {
int tmp = heap.a[index];
heap.a[index] = heap.a[index/2];
heap.a[index/2] = tmp;
}
else {
break;
}
}
}
int deleteMin() {
int min = heap.a[1];
int i = 1;
int index = 1;
int lastData = heap.a[heap.size];
while(true) {
if(i*2+1 <= heap.size) {
if(heap.a[i*2] < heap.a[i*2+1]) {
heap.a[i] = heap.a[i*2];
i = i*2;
}
else {
heap.a[i] = heap.a[i*2+1];
i = i*2+1;
}
}
else if(i*2 <= heap.size) {
heap.a[i] = heap.a[i*2];
i = i*2;
}
else {
break;
}
}
heap.a[i] = lastData;
heap.size -= 1;
return min;
}
void print() {
for(int i=1; i <= heap.size; i++) {
std::cout << heap.a[i] << ",";
std::cout << std::endl;
}
}
int main() {
initHeap();
insert(9);
insert(8);
insert(7);
insert(6);
insert(5);
insert(4);
//print();
deleteMin();
print();
return 0;
}
堆是一棵被完全填满的二叉树(完全二叉树),它的任意节点小于它的子节点,它的插入,删除操作时间复杂度为O(log2N);