0

So I've been struggling with this for some time now and now I feel I'm totally stuck. I'm done with selection sort and binary search in helpers.c, and I think they are working all right. Actually for some time they almost used to, the program did find the bloody needle but it didn't say anything when the needle was not in the haystack, so I fiddled around with it, and now it just doesn't do anything anymore. It compiles, it lists the pseudo-random haystack items and bamm, nothing. Only ctrl+c helps. Same in gdb, when I give the input manually, doesn't do anything for ctrl+d. For check50 it says "unexpected end of input". I'm really, really lost and have no idea how to proceed. Please help :) And here's the code itself:

bool search(int value, int values[], int n)
{

   if (n < 0)
   {
      return 1;
   }
   while (n >= 0)
   {
    int start = 0;
    int finish = n-1;
    int mid = (start + finish)/2;
    if (values[mid] == value)
        return true;
    else if (values[mid] < value)
    // if value is higher than mid, search right
    {
        start = mid + 1;
        bool search(int value, int values[], int n);

    }
    else if (values[mid] > value)
    // if value is lower than mid, search left 
    {
        finish = mid - 1;
        bool search(int value, int values[], int n);

    }

}

return false; }

And this is the sorting thingy:

void sort(int values[], int n) {

for (int i = 1; i < n; i++)
{
    int element = values[i];
    int j = i;
    while (j > 0 && element < values[j-1])
    {
        values[j] = values [j-1];
        j = j-1;
        values[j] = element;
    }
}
return;
2
  • Consider adding your source code, we can't possibly figure out what is wrong, although it sounds like an infinite loop somewhere to me.
    – ChrisG
    Commented Aug 25, 2015 at 11:06
  • @ChrisG thanks, I added it :)
    – nattakiri
    Commented Aug 25, 2015 at 11:20

1 Answer 1

1

You while-loop never finishes because n never changes. You need to either rethink your logic so the loop terminates when the value was not found, returning false, or detect when there's no values left to search inside the loop, and then return false. If you still want to go with the recursion-route, you need to change n when you call the function again. I think there's more elegant solutions however. Take a look at the Binary Search short by Patrick so you can understand the algorithm better. You can't copy his solution 1:1, since you can't change the function arguments, but you can learn and modify it so it fits your function. Just make sure you understand the algorithm fully before you start coding.

You must log in to answer this question.

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