Hi guys, I'm brand brand new to this forum, so excuse me if I make any newbie mistakes. I try to look over the FAQs and important posts before posting, but you're still forewarned. Anyways, I'm working on a homework assignment for a second-semester Intro to CS class and we have to make a heap with an array of size 20 which stores the smallest priority on the top. So it's just a min-heap. But for some reason, I get a segmentation fault/ assertion failed because I believe my left() function is wrong. Also, my insert() function isn't resorting the heap after an object is inserted and I don't think my reheapify function is in any working order either. I have such a hard time proofreading my work and was wondering if I could get some second eyes for help.
Code:
Heap::Heap() {
heapSize = 0;
int t = 0;
while (t < heapMaxSize) {
array[t].priority = -1;
t++;
}
}
int Heap::left(int p) const {
assert(p < (heapSize - 1)/2);
return (p * 2) + 1;
}
int Heap::right(int p) const {
assert(p < (heapSize - 1)/2);
return (p * 2) + 2;
}
int Heap::parent(int p) const{
assert (p != 0);
return (p - 1) / 2;
}
void Heap::insertHeapItem(int i) {
if (isFull()) // Stack Overflow exception
cout << "Error: Stack Overflow Error \n"; // FIX THIS LATER
HeapItem newItem; // Creates new item
newItem.priority = i; // Sets priority
array[heapSize] = newItem; // next open array position gets item
int positionNew = heapSize; // Moves position up one
heapSize++; // increments size
// while positionNew is not the root and is greater than its parent
while (positionNew != 0 and (array[positionNew].priority
< array[parent(positionNew)].priority)) {
swap(array[positionNew], array[parent(positionNew)]); // Swap positions
positionNew = parent(positionNew);
}
}
HeapItem Heap::removeMin() {
assert (!isEmpty());
heapSize--;
if (heapSize != 0) { // If there's more than just the root
swap(array[0], array[heapSize]); // Switch largest with smallest
reHeap(0); // rearrange to proper places
}
return array[heapSize]; // Take off last(lowest) heap item
}
void Heap::reHeap(int p) {
int leaf = left(p);
if ((array[leaf].priority > array[leaf + 1].priority) and
(leaf < heapSize - 1))
leaf++;
if (array[p].priority <= array[leaf].priority)
;
swap(array[p], array[leaf]);
reHeap(leaf);
}
void Heap::swap(HeapItem a, HeapItem b) {
HeapItem temp = a;
a = b;
b = temp;
}
HeapItem is a separate class with just an int that's called priority.
If you're looking to see my driver, here is the code:
Code:
int main() {
Heap test;
HeapItem temp;
int n = 0;
test.insertHeapItem(3);
while (n < heapMaxSize) {
cout << test.priority(n) << " ";
n++;
}
cout << '\n';
n = 0;
test.insertHeapItem(20);
while (n < heapMaxSize) {
cout << test.priority(n) << " ";
n++;
}
cout << '\n';
n = 0;
test.insertHeapItem(1);
while (n < heapMaxSize) {
cout << test.priority(n) << " ";
n++;
}
cout << '\n';
n = 0;
temp = test.removeMin();
cout << '\n' << temp.priority;
return 0;
}
Thank you so much for any help in advance!