gpt4 book ai didi

C:堆排序算法,删除&插入

转载 作者:太空宇宙 更新时间:2023-11-04 03:47:05 25 4
gpt4 key购买 nike

所以我要为类写一个堆数据结构,它应该只使用插入和删除操作来实现堆排序。

它适用于 .. 较小的整数集(大小为 10 及以下)。但是,当我输入一大组数字(100+)时,结果只是半排序..

这是我的插入方法:

 void insert(heapHndl H, int priority) {
// Makes sure heap has enough room for new element.
assert(!isFull(H));
// Increase the current size.
H->currentSize++;
// Add to array.
int pos = H->currentSize;
// Work up.
while (pos > 1 && priority < H->array[pos/2]) {
swap (H, pos, pos/2);
pos /= 2;
}
H->array[pos] = priority;
}

这是我的删除方法:

 void deleteMax(heapHndl H) {
// Makes sure the heap is not empty.
assert(!heapEmpty(H));

int root = 1;
// Swap the root and last element.
swap(H, root, H->currentSize);
H->array[H->currentSize] = -1;
H->currentSize--;

// Work your way down from the root.
while(root != H->currentSize) {
int leftChild = 2*root;
int rightChild = 2*root + 1;
int minChild;
// If root is smaller than children..
if (H->array[root] <= H->array[leftChild] &&
H->array[root] <= H->array[rightChild])
break;
// If at a leaf node.
if (rightChild > H->currentSize){
if (leftChild >= H->currentSize)
break;
else minChild = leftChild;
} else {
// Determines which child to swap with.
if (H->array[leftChild] <= H->array[rightChild])
minChild = leftChild;
else minChild = rightChild;
}
swap(H, root, minChild);
root = minChild;
}
}

这里是 heapHndl。

 typedef struct HeapStruct {
int maxSize;
int currentSize;
int *array;
} HeapStruct;

typedef HeapStruct* heapHndl;

我似乎无法弄清楚删除方法还缺少哪些其他情况。我很确定我的插入方法没问题(手动检查)。谢谢您的帮助。编辑:忽略名称 deleteMax。它实际上是一个最小堆。根是最小的整数。

最佳答案

下面两行肯定有问题

     if (leftChild > H->currentSize || rightChild > H->currentSize)
break;

如果其中一个 child 丢失,循环不允许中断,只有当两个 child 都丢失时。如果右 child 丢失,您仍然必须检查,并可能与左 child 交换。


编辑:另一方面,如果父节点是三者(父节点、左节点、右节点)中最小的节点,则循环确实需要中断。

关于C:堆排序算法,删除&插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23420304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com