I am trying to write a down heap function for my heap but it keeps getting stuck in an infinite loop and I'm not sure why. also, i am not sure how to make it so it doesn't check outside of my last variable which is part of the problem i think
this is where it gets stuck
else if(2*i+1 <= last&& arr[2*i+1]!=0 && 2*i > last)
void heap::downheap()
{
int temp= 0;
int i = 1;
while(i < last)
{
// if(2*i > last|| 2*i+1 >last){
// cout<< "error"<<endl;
//}
if(2*i <= last && 2*i+1 <=last){
if(arr[i] < arr[2*i] && arr[2*i] > arr[2*1+1])
{
cout<< "left";
temp = arr[i];
arr[i] = arr[2 *i];
arr[2*i] = temp;
if(arr[i*2] > arr[i*2+1])
i = i*2;
else
i = i * 2+1;
}
else if(arr[i] < arr[i*2+1] && arr[2*i+1] > arr[2*1])
{
cout<< "right";
temp = arr[i];
arr[i] = arr[2 *i+1];
arr[2*i+1] = temp;
//i++;// = i*2+1;
if(arr[i*2+1] > arr[i*2])
i = i*2+1;
else
i = i * 2;
}
else if(arr[i] > arr[i*2] || arr[i*2+1])
{
if(arr[i*2+1] > arr[i*2])
i = i*2+1;
else
i = i * 2;
}
}
else if(2*i <= last && arr[2*i]!=0 && 2*i+1 > last)
{
temp = arr[i];
arr[i] = arr[2 *i];
arr[2*i] = temp;
//i++;// = i*2;
if(arr[i*2] > arr[i*2+1])
i = i*2;
else
i = i * 2+1;
}
else if(2*i+1 <= last&& arr[2*i+1]!=0 && 2*i > last)
{
temp = arr[i];
arr[i] = arr[2 *i+1];
arr[2*i+1] = temp;
//i++;// = i*2+1;
if(arr[i*2+1] > arr[i*2])
i = i*2+1;
else
i = i * 2;
}
}
}
this is as far as i get -1 to remove 0 to stop: -1 removed 8 7 1 6 4 3 2 5 -1 to remove 0 to stop: -1 removed 7 6 1 2 4 3 5 -1 to remove 0 to stop: -1