0

I am working on Pset3 for a binary search algorithm. Below is my code (NOTE: the logic is not finished):

bool search(int value, int values[], int n)
{
//binary search algorithm
int min = 0;
int max = n-1;
int midpoint;
int midpoint2 = 0;
midpoint2 += 0;
if ((n-1) % 2 == 0) {
    midpoint = (max+min)/2;
}
else {
    midpoint = (int) (max+min)/2; 
    midpoint2 = ((int) (max+min)/2) + 1;
}
printf("min: %i, max: %i, mid: %i\n", min,max,midpoint);
return true;
bool sorted = false;
do {
    printf("beginning loop");
    if (values[midpoint] == value || values[midpoint2] == value) {
        return true;
        printf("1");
    }
    else if (n == 1) {
        return false;
        printf("2");
    }
    else{
        for (int c = midpoint - 1 ; c < n - 1 ; c++ ) {
            int b = values[c];
            values[c] = values[c+1];
            printf("value index %i used to be %i\n",c,b);
            printf("value index %i is now %i\n",c,values[c]);
        }
    }
}
while (sorted == false);
}

When I run find.c, my do-while loop never actually executes. I have tested this by placing the debug print statement "beginning loop", which never prints to the screen. I never see 1, 2, or "value index.. " print statements either. Please help!

2

Right before bool sorted = false;, you have return true;. You give a return value before anything else happens, so your function does exactly that: it returns that value and stops executing any further code.

2
  • Peter is absolutely right. Remember that anytime a return statement is encountered, processing in that function or program will immediately cease and program flow will immediately return to the calling code (or in the case of main, to the operating system.)
    – Cliff B
    Feb 26 '16 at 23:21
  • Thanks! The program now works.
    – jaguar
    Feb 27 '16 at 18:18

You must log in to answer this question.

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