将堆作为参数传递

问题描述 投票:0回答:1

我试图制作几个函数,这些函数通过以下代码将堆作为参数传递。但是,它并没有达到我的预期。

#include<stdio.h>

void upHeap_min2 (int *heap, int index)
{
    if (index == 0)
        return;

    int parentIdx = getParentIdx(index);
    if (heap[index] < heap[parentIdx])
    {
        int temp = heap[index];
        heap[index] = heap[parentIdx];
        heap[parentIdx] = temp; 

        upHeap_min2(heap, parentIdx);
    }
}

void pushValue (int *heap, int count, int value)
{
    count++;
    heap[count] = value;
    upHeap_min2(heap, count);   
}

void view(int *heap, int count)
{
    printf("Values inside heap: ");
    for (int i = 0; i < count; i++)
    {
        printf("%d ", heap[i]);
    }
    printf("\n");
}

int main()
{
    int heapDemo[101];
    int count = -1;
    pushValue(heapDemo, count, 30);
    pushValue(heapDemo, count, 20);
    pushValue(heapDemo, count, 40);
    pushValue(heapDemo, count, 90);
    pushValue(heapDemo, count, 10);

    view(heapDemo, count);

    return 0;
}

获得父索引的功能:

int getParentIdx (int index)
{
    return (index-1)/2;
}

上面的代码应该已经打印

10 20 40 90 30

但是它什么也不打印。我也曾考虑将其作为双指针传递,但我没有工作。这是否意味着我无法将堆作为参数传递(这意味着我必须将堆声明为全局变量),或者还有另一种方法?]

我试图制作几个函数,这些函数通过以下代码将堆作为参数传递。但是,它并没有达到我的预期。 #include void upHeap_min2(...

c arrays heap
1个回答
0
投票

这是一个有效的解决方案,让我解释一下

© www.soinside.com 2019 - 2024. All rights reserved.