0

I need advice as to what to change in this code to make it work. I am new at this so I need specifics, please. Please, no opinions on whether it's trash or what mark you would give if grading it. That doesn't help. We all have to start somewhere. I gather it needs an outer loop. Can anyone suggest how to do this. What type of loop would you suggest?

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

int min = 0; int max = n - 1; int mid = (max + min) / 2;

if (n >= 0) { if (values[mid] == value) { return true; }

else if (values[mid] > value)
{
    for (int i=0; i <=(mid); i++) //to search left half
    {
        if (i == value)
        {
            return true;
        }
    }
}

else if (values[mid] > value)
{
    for (int i = (mid); i < (max); i++) //search right half
    {
        if (i == value)
        {
            return true;
        }
    }
}
else
{
    return false;
}

}
return false; } /////////////////////////

This is an example from the check50 result:

:( finds 42 in {42,43,44} \ expected an exit code of 0, not 1

:) finds 42 in {41,42,43}

1

Here is Zamyla's pseudocode for search

while (length of list > 0)
     look at middle of list
     if number found, return true
     else if number higher, search left
     else if number lower, search right
return false
  • try changing your outer if (n >= 0) loop to a while loop.
  • I recommend removing the for loop. The point of this search is to save time and iterating over each element is wasting time.

I hope this helps you get back on the right track with the loops.

| improve this answer | |
  • Thanks for your help. I'll try your suggestions. :^) – Android1 Mar 30 '17 at 6:26

You must log in to answer this question.

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