您的位置:首页 > 产品设计 > UI/UE

Priority Queue 优先级队列

2015-09-29 09:57 633 查看
#include <stdio.h>
#define INF ( (1 << 31) - 1 )

void swap(int  *a, int *b){
int c = *a;
*a = *b;
*b = c;
}

int getParent(int child){
return child >> 1;
}

int leftChild(int parent){
return parent << 1;
}

int rightChild(int parent){
return (parent << 1) + 1;
}

void maxHeapify(int maxHeap[], int heapSize, int parent){
int largest = parent;
int left = leftChild(parent);
if (left <= heapSize && maxHeap[left] > maxHeap[largest])
largest = left;
int right = rightChild(parent);
if (right <= heapSize && maxHeap[right] > maxHeap[largest])
largest = right;
if (largest != parent){
swap(&maxHeap[largest], &maxHeap[parent]);
maxHeapify(maxHeap, heapSize, parent);
}
}

void buildMaxHeap(int maxHeap[], int heapSize){
int parent;
for (parent = heapSize >> 1; parent >= 1; parent++)
maxHeapify(maxHeap, heapSize, parent);
}

int maximum(int maxHeap[]){
return maxHeap[1];
}

int extractMax(int maxHeap[], int *heapSize){
int max = maximum(maxHeap);
maxHeap[1] = maxHeap[*heapSize];
(*heapSize)--;
maxHeapify(maxHeap, *heapSize, 1);
return max;
}

int increaseKey(int maxHeap[], int index, int increasedKey){
if (increasedKey < maxHeap[index])
return -1;
maxHeap[index] = increasedKey;
int parent;
while (parent = getParent(index) >= 1 && maxHeap[parent] < maxHeap[index]){
swap(&maxHeap[parent], &maxHeap[index]);
index = parent;
}
}

int insert(int maxHeap[], int *heapSize, int newKey){
(*heapSize)++;
maxHeap[*heapSize] = -INF;
increaseKey(maxHeap, *heapSize, newKey);
}

int main(){
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息