【问题标题】:Inserting elements in a Priority Queue using a Heap使用堆在优先级队列中插入元素
【发布时间】:2013-12-03 08:35:42
【问题描述】:

我想在优先级队列中插入元素以便对它们进行排序,但我没有正确使用 min_heapify 函数。到目前为止,这是我的代码:-

#include <stdio.h>
#include <stdlib.h>
struct entity{ //An entity consists has its data and its priority
    int data; 
    int priority;
};
void swap(int *a ,int *b){
    int temp = *a; *a = *b; *b = temp;
}
void min_heapify(struct entity a[], int p){
    int r = (p+1)*2, l=r-1, smallest = p; //p is parent, r is right child and l is left child
    if(l < p && a[l].priority < a[p].priority) smallest = l;
    if(r < p && a[r].priority < a[smallest].priority) smallest = r;
    if(smallest != p){
        swap(&a[p].data, &a[smallest].data); //swap child and parent if parent isn't the smallest
        swap(&a[p].priority, &a[smallest].priority);
        min_heapify(a, smallest); //Keep on calling same method until parent is the smallest
    }
}
void display(struct entity a[], int count){
    printf("The Queue is:-\n");
    if(count == 0) printf("Empty.");
    else for(int i = 0; i < count; i++)
        printf("\n%d\t(priority: %d)\n", a[i].data, a[i].priority);
}
int main(){
    int n, count = 0, choice;
    printf("Enter the size of the priority queue: ");
    scanf("%d", &n);
    struct entity *a = (struct entity*)malloc(sizeof(struct entity) * n);
    while(1){
        display(a, count);
        printf("1.Insert 2.Exit: ");
        scanf("%d", &choice);
        switch(choice){
            case 1: if(count < n){
                        printf("\nEnter the number and its priority:-\n");
                        scanf("%d%d", &a[count].data, &a[count].priority);
                        min_heapify(a, (++count)/2);
                    }break;
            case 2: return 0;
        }
    }
}

【问题讨论】:

  • 您是否尝试过在调试器中逐行执行代码?如果没有,那就这样做吧,希望能帮助你缩小问题的范围。

标签: c logic heap runtime-error priority-queue


【解决方案1】:

您的*a 未初始化,因此包含随机数据。在min_heapify() 中,您连续两次传递同一个父级。因此,您的 lr 对于 2 个呼叫是相同的。但是r 对第一次通话无效!。它有随机数据。

打电话时建议使用min_heapify(int index, int size)。在顶部调用 min_heapify(count, count); count++; 在 min_heapify() 中,您可以使用 indexsize 值来了解 parent (index/2) 是否具有 right (index

【讨论】:

    猜你喜欢
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    • 2018-04-10
    相关资源
    最近更新 更多