码迷,mamicode.com
首页 > 编程语言 > 详细

c语言优先队列的实现

时间:2020-01-21 17:52:47      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:down   ++   pre   优先队列   c语言   oid   com   include   mem   

优先队列即二叉堆,实现如下:

 

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

typedef int Element;
#define MAX_BINHEAP_LENGTH 10

struct BinaryHeap {
    Element array[MAX_BINHEAP_LENGTH];
    int length;
};

int compare(const void* a, const void* b)
{
    // minimul
    return *(int*)a - *(int*)b;
    // maximul
    // return *(int*)b - *(int*)a;
}

void percolateDown(struct BinaryHeap* heap, int hole)
{
    int child;
    Element temp = heap->array[hole];

    for (; hole * 2 <= heap->length; hole = child) {
        child = hole * 2;
        if (child != heap->length && compare(&(heap->array[child + 1]), &(heap->array[child])) < 0) {
            child++;
        }
        if (compare(&(heap->array[child]), &temp) < 0) {
            heap->array[hole] = heap->array[child];
        } else {
            break;
        }
    }
    heap->array[hole] = temp;
}

void buildBinaryHeap(struct BinaryHeap* heap, Element* array, int length)
{
    if (array == NULL || length == 0) {
        memset(heap, 0, sizeof(struct BinaryHeap));
        return;
    }

    for (int i = 0; i < length; i++) {
        heap->array[i] = array[i];
        heap->length = length;
    }

    for (int i = heap->length / 2; i > 0; i--) {
        percolateDown(heap, i);
    }
}

int isEmpty(struct BinaryHeap* heap)
{
    return heap->length == 0;
}

void insert(struct BinaryHeap* heap, Element elem)
{
    int hole = ++(heap->length);
    for (; hole > 1 && compare(&elem, &(heap->array[hole / 2])) < 0; hole /= 2) {
        heap->array[hole] = heap->array[hole / 2];
    }
    heap->array[hole] = elem;
}

// here is deleteMinimul, if deleteMaximul, change it!
void deleteMinimul(struct BinaryHeap* heap)
{
    if (heap->length == 0) {
        return;
    }
    heap->array[1] = heap->array[heap->length--];
    percolateDown(heap, 1);
}

// here is deleteMinimul, if deleteMaximul, change it!
Element getMinimul(struct BinaryHeap* heap)
{
    return heap->array[1];
}

int main()
{
    int array[8] = { 0, -13, 5, 23, -9, -2, 4, -6 };
    struct BinaryHeap heap;
    buildBinaryHeap(&heap, array, 8);
    while (!isEmpty(&heap)) {
        Element elem = getMinimul(&heap);
        deleteMinimul(&heap);
        printf("%d\n", elem);
    }
    return 0;
}

c语言优先队列的实现

标签:down   ++   pre   优先队列   c语言   oid   com   include   mem   

原文地址:https://www.cnblogs.com/tongyishu/p/12222540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!