下面是我插入堆的C ++代码。插入k的值,但它插入底部。我期望它与while循环堆积。
void Insert(heap1* myHeap, int k)
{
(myHeap->size)++;
int i = myHeap->size;
while (i > 1 && myHeap->H[i/2].key < k)
{
myHeap->H[i].key = myHeap->H[i/2].key;
i = i/2;
}
myHeap->H[i].key = k;
}
我确实有一个我尝试在此尝试之前使用的heapify过程,我知道在我的其他堆过程中工作。我只是无法让它在Insert中工作,所以我选择了上述路线。下面是heapify,以防它有用:
void heapify(heap1* myHeap, int i)
{
int l = 2 * i;
int r = 2 * i + 1;
int largest;
if (l <= myHeap->size && myHeap->H[l].key > myHeap->H[i].key)
largest = l;
else
largest = i;
if (r <= myHeap->size && myHeap->H[r].key > myHeap->H[largest].key)
largest = r;
if (largest != i)
{
myHeap->H[i].key = myHeap->H[i].key + myHeap->H[largest].key;
myHeap->H[largest].key = myHeap->H[i].key - myHeap->H[largest].key;
myHeap->H[i].key = myHeap->H[i].key - myHeap->H[largest].key;
heapify(myHeap, largest);
}
}
如果有人能够指导我如何让它恢复其堆属性,我会非常感激。
答案 0 :(得分:0)
尝试使用此代码:
void insert(int heap[], int *n, int item){
(*n)++;
heap[*n] = item;
reheapify_upward(heap, *n);
}
void reheapify_upward(int heap[],int start){
int temp,parent;
if(start>1){
parent=start/2;
if(heap[parent]<heap[start]){
temp=heap[start];
heap[start]=heap[parent];
heap[parent]=temp;
reheapify_upward(heap,parent);
}
}
}