So I'm to write a heap data structure for class, and it's supposed to implement heap sort using only insert and delete operations.
It works .. for smaller sets of ints (size 10 and below). However, when I input a large set of numbers(100+) in, the result is only semi sorted..
Here's my insert method:
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;
}
Here's my delete method:
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;
}
}
Here's heapHndl.
typedef struct HeapStruct {
int maxSize;
int currentSize;
int *array;
} HeapStruct;
typedef HeapStruct* heapHndl;
I can't seem to figure out what other cases I'm missing for the delete method. I'm pretty sure my insert method is fine (manual checking). Thanks for the help. Edit: ignore the name, deleteMax. It's actually a min heap. Root is the smallest integer.
heapHndl?int root = 1;is very suspicious.int *array;and yet I see statements like: ` H->array[pos/2])` and ` H->array[pos/2])` Have you used any malloc() or calloc() calls? If so, how much memory did you allocate?m(c)alloc()statements. Nor is there atmp->array. It would help to see them in context. You might re-think how you are presenting this question, and after doing some of your own debugging, if the problem persists, re-post. Here are some suggestions on how to improve a post.