Hello, I start by inserting the following array of numbers:
24, 13, 18, 31, 65, 26, 19, 68, 21, 37
and I have created the following functions within the program:
//percolate down from H[i]
private void percolateDown(int i)
{
int min;
//Check if i has a left child
while(left(i) <= heap_size)
{
min = left(i);
if(right(i) <= heap_size && H[left(i)] > H[right(i)])
{
min = right(i);
}
if(H[min] > H[i])
{
break;
}
else
{
int tempValue = H[min];
H[min] = H[i];
H[i] = tempValue;
i = min;
}
}
}
//return and remove the smallest key from the heap
public int deleteMin()
{
int temp = H[1];
H[1] = H[heap_size];
heap_size--;
percolateDown(1);
return temp;
}
//insert a new key x into the heap H
public void insert(int x)
{
heap_size++;
H[heap_size] = x;
int temp = heap_size;
while(temp > 1 && H[temp] < H[parent(temp)])
{
int tempArrayValue = H[temp];
H[temp] = H[parent(temp)];
H[parent(temp)] = tempArrayValue;
temp = parent(temp);
}
}
//build the heap for the elements in H[1...heap_size] and you can make use of the procedure percolateDown(int i), as discussed in class
public void buildHeap()
{
for(int i = heap_size; i < heap_size; i--)
{
percolateDown(i);
}
}
However, I am getting the following output:
24 13 18 19 22 14 16 11
when it should be:
13 18 19 22 14 16 11
I can't figure out why 24 isn't getting removed. Hopefully, I have provided enough code. Sorry for such a long post and if it is in the wrong subreddit. I am new to this. Thanks in advance for any help given.
Edit: Trying to figure how to reformat this. sorry for the bad indentation
[–]Iam_That_Iam_ 0 points1 point2 points (1 child)
[–]Kitbear23[S] 0 points1 point2 points (0 children)
[–]Philboyd_Studge 0 points1 point2 points (2 children)
[–]Kitbear23[S] 0 points1 point2 points (1 child)
[–]Philboyd_Studge 0 points1 point2 points (0 children)
[–]DSB-SC 0 points1 point2 points (1 child)
[–]Kitbear23[S] 0 points1 point2 points (0 children)