0

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

cdude
  • 41
  • 6
  • Look like this: `else if(arr[i] < arr[i*2+1] && arr[2*i+1] > arr[2*1])` has a typo! Do you *really* mean `2*1` as the last index - or `2*i`? – Adrian Mole Nov 07 '19 at 18:26
  • i did mean `2*i` and now my code is getting stuck `else if(2*i+1 <= last&& arr[2*i+1]!=0 && 2*i > last)` in this statement – cdude Nov 07 '19 at 18:34
  • 1
    Use your debugger and step through your program to determine where your program deviates from your expectations. *i am not sure how to make it so it doesn't check outside of my last variable which is part of the problem* -- Then step away from the computer and work this out with pencil and paper. You should have all of the known cases already figured out with pencil and paper first before writing a program. – PaulMcKenzie Nov 07 '19 at 18:48

0 Answers0