堆及其应用（优先级队列，TopK问题，堆排序）

堆创建

void Adjust(Heap *heap, int parent)
{
assert(heap);
int child = parent * 2 + 1;
while (child < heap->size) {
int right = child +1;
//得到左右孩子较小的
if (right < heap->size) {
if (heap->compare(heap->array[right] , heap->array[child])) {
child = right;
}
}
//与父交换，或者调整完毕
if (heap->compare(heap->array[child], heap->array[parent] )) {
swap(&heap->array[parent], &heap->array[child]);
parent = child;
child = child * 2 + 1;
}
else {
return;
}
}
}

插入元素

void InsertHeap(Heap *heap, DataType data)
{
assert(heap);
if (heap->size == heap->capacity) {
//扩容,没使用realloc
int newCap = 2 * heap->capacity;
DataType *pNew = (DataType*)malloc(sizeof(DataType)*newCap);
if (NULL == pNew) {
exit(EXIT_FAILURE);
}
int i = 0;
for (i = 0; i < heap->size; i++) {
pNew[i] = heap->array[i];
}
heap->array = pNew;
heap->capacity = newCap;
}
heap->array[heap->size++] = data;
//向上调整
int parent = (heap->size - 2) >> 1;
int cur = heap->size - 1;
while (parent >= 0) {
if (heap->compare(heap->array[cur], heap->array[parent])) {
swap(&heap->array[parent], &heap->array[cur]);
cur = parent;
parent = (parent - 1) >> 1;
}
else {
return;
}
}
return;
}

删除元素

void DeleteHeap(Heap *heap)
{
assert(heap);
if (heap->size > 1) {
swap(&heap->array[0], &heap->array[heap->size - 1]);
heap->size--;
int i = 0;
int end = (heap->size - 2) >> 1;
}
else if(heap->size ==1){
heap->size--;
}
}

TopK问题

void TopK(int data[], int len, int top[])
{
const int MaxLen = 5;
Heap heap;
InitHeap(&heap, Less);
CreateHeap(&heap, data, MaxLen);
int res = len - MaxLen; //剩余需要处理的元素个数
//维护一个只有五个数值的堆
while (res) {
if (data[len - res] > TopHeap(&heap)) {
DeleteHeap(&heap);
InsertHeap(&heap, data[len - res]);
}
res--;
}
//此时堆元素就是最大的5个元素
int i = 0;
for (i = 0; i < 5; i++) {
top[i] = TopHeap(&heap);
DeleteHeap(&heap);
}
}

堆排序

void HeapSort(int array[], int len)
{
if (NULL == array) {
return;
}
//建立大根堆
Heap heap;
InitHeap(&heap, Less);
CreateHeap(&heap, array, len);
//堆顶元素放数组末尾，移除堆顶元素，调整堆顶元素
while (len--) {
array[len] = TopHeap(&heap);
DeleteHeap(&heap);
}
DestroyHeap(&heap);
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120