这里讲述的是用堆实现的最大优先级队列,创建的是最大堆,主要实现3个算法,一个是抽取对头元素,也就是整个堆里面最大的那个数,还有一个是提升某个节点的优先级,最后是往队尾插入元素。算法
一、创建最大堆数组
void build_max_heap(int *a, int i, int n) { int max = i; int left = 2 * i + 1; int right = 2 * i + 2; if (left < n && a[left] > a[max]) { max = left; } if (right < n && a[right] > a[max]) { max = right; } if (i != max) { int temp = a[i]; a[i] = a[max]; a[max] = temp; build_max_heap(a, max, n); } }
二、抽取对头元素ide
int extract_max(int *a, int n) { int max = a[0]; a[0] = a[n-1]; build_max_heap(a, 0, n-1); return max; }
三、将队列中的某个元素的优先级提升ui
int increase_key(int *a, int i, int key) { if (key < a[i]) { return -1; } a[i] = key; int p; while (i > 0 && a[p=(i-1)/2] < a[i]) { int temp = a[p]; a[p] = a[i]; a[i] = temp; i = p; } return 0; }
四、队尾插入元素队列
void heap_insert(int *a, int n, int key) { int i = n; a[i] = key; int p; while (i > 0 && a[p=(i-1)/2] < a[i]) { int temp = a[p]; a[p] = a[i]; a[i] = temp; i = p; } }
注意在插入的时候,要确保数组有足够的存储空间,n是当前数组元素的下一个位置it