小编unt*_*led的帖子

最小堆插入函数

这是最小堆的插入函数。我不明白为什么它不起作用。

void insertHeapMin(Heap* h, int x){
if(isFull(h)){
    printf("heap is full\n");
    return;
}
for(i=0; i<h->size;i++) //I don't wan't to insert one number more than once; 
{
    if(x==h->data[i]) return;
}
int pos = h->size;
h->data[pos]=x;
while(pos>0){
    int parentPos = (pos-1)/2; 
    if (h->data[pos] < h->data[parentPos]){
        int temp = h->data[pos];
        h->data[pos] = h->data[parentPos];
        h->data[parentPos] = temp;
        pos = parentPos;
    } else
        break;
}
h->size++;
}
Run Code Online (Sandbox Code Playgroud)

主要的:

int a[] ={4,3,6,4,5};
size_t n = sizeof(a)/sizeof(a[0]);
Heap h;
initHeap(&h,100);
int i;
for(i=0;i<n;i++){
    insertHeapMin(&h, a[i]);
}
for(i=0;i<n;i++){
    printf("%d …
Run Code Online (Sandbox Code Playgroud)

c heap

1
推荐指数
1
解决办法
120
查看次数

标签 统计

c ×1

heap ×1