有人可以改进我的堆数据结构代码吗?

时间:2016-08-21 07:56:13

标签: c data-structures heap

我正在尝试从随机数组构建最大堆,以便我可以在根中获得最大数量。

另外请告诉我,如何在heapify()函数中获取堆的大小。

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

int i;
void heapify(int a[],int i)    //n=node at which heapify needs to apply
{
    int size=8;
    int max=i,l=2i,r=2i+1;
    if(a[l]>a[max] && l<=size)
    max=l;
    if(a[r]>a[max] && r<=size)
    max=r;
    if(max==i) return;
    else
    a[max]^=a[i]^=a[max]^=a[i];
    heapify(a,max);
}

//Using this function to call recursively  heapify to maintain heap data structure
void build_heap(int arr[],int n)   //n : size of array
{
    for(i=floor(n/2);i>0;i--)    // n/2 because after that every node is a leaf node and they follow heap property by default
    {
        heapify(arr,i);
    }
}

int main()
{
    int arr[] = {2,5,4,8,9,10,3,1};
    build_heap(arr,8); 
    for(i=0;i<8;i++)
    {
            printf("%d ",arr[i]);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

除了一些变化之外,您的代码似乎没有问题:

  • 2i2i+1更改为2*i2*i+1,否则您将收到编译错误。实际上它应该是l = 2*i+1r = 2*i+2,因为C数组是0-indexed。您假设代码中有1-based索引。
  • build_heap()中,运行[floor(n/2), 0]的循环(您排除了0&#39;元素可能是因为上述原因所述。)

您可以将堆的大小作为参数传递给heapify()函数,或将其声明为全局变量(尽管建议避免使用全局变量)。

相关问题