c语言优先队列的实现

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

#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;
}

猜你喜欢

转载自www.cnblogs.com/tongyishu/p/12222540.html