0

I have an issue with the "find" problem. When I test my program, it seems to get stuck in an infinite loop (nothing is prompted, there is just a blank space and I have to kill the program with ctrl c). I have read so many threads, tried many differents fixes, but nothing seems to work. I feel it's something in my sorting algorithm, but I'm not completely sure. Can anyone point me in the right direction? I'm really lost on this one!

Here is the searching algorithm:

#include <cs50.h>

#include "helpers.h"


int end, beg, mid;
bool search(int value, int values[], int n)
{
    end = n-1;
    beg = 0;
    mid = (end + beg /2);            

while (end >= beg)                   
{
    if (values[mid] == value)        
    {
        return true;
    }

    else if (values[mid] < value)   
    {
        beg = mid + 1;
    }

    else                             
    {
         end = mid - 1;
    }
}

return false; 

}

And here is my selection sort algorithm, which I think is the one with the problem:

int small, swap;
void sort(int values[], int n)
{
for (int i=0; i <= n-2; i++)               
{
   small = i;

    for (int j = i + 1; j < n; j++)
    {
        if (values[j] < values[small])
        {
            small = j;
        }
    }

    if (small != i)
    {
        swap = values[small];
        values[small] = values[i];
        values[i] = swap;
    }

}

return;

}

Thank you so much for your help, I'm really getting crazy on this one!

1

In search, move the calculation of mid into the loop, and make sure the /2 is outside the parentheses.

The sorting algorithm has no potential for an infinite loop, and looks correct.

Also, it's usually best to have as few global variables (declared outside of any function) as possible.

3
  • Thank you!!! I feel stupid not thinking about it! And regarding your last remark, I'm not sure I understand, what variable could I make global? – Manon H Mar 4 '17 at 18:27
  • You have several variables like end that are declared outside of the function, therefore global, while there's no reason for making them global. Having many global variables might cause unmaintainable code. – Blauelf Mar 5 '17 at 0:22
  • Ok I get it now! Thanks! – Manon H Mar 6 '17 at 15:00
0

You have two problem 1- the calculation for division goes first so mid = (beg + end / 2) is actually doing this end/2 and the result will be add to beg 2- your mid point will always stay the same as you've assigned it out side the loop, you need it inside the loop so that every time you change the beg and end you update the mid as well

1
  • Thank you so much! – Manon H Mar 4 '17 at 18:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .