C Binary search

Caroline

My binary search program compiles, but something is wrong with my algorithm. For example, if I try to find 9 in the list 2 5 7 8 9 10, my program says that there is no 9 in the list. Where have I gone wrong?

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int valuetofind, n, list [100];
bool found, notinthelist;

int binary_search () {
    int middle, p = 0, q = n-1;

    middle = (p + q) / 2;
    while ( (found == false) && (notinthelist == false) ) {
        if (list[middle] == valuetofind) {
            found = true;
            printf("%d is the %d element\n", valuetofind, middle+1);
        }
        else {
            if (n < list[middle] )  q = middle - 1;
            else p = middle + 1;

            if (p > q) {
                notinthelist = true;
                printf("%d is not in this list\n", valuetofind);
            }
        }
        middle = (p + q) / 2;
    }
}

int main () {
    found = false;
    notinthelist = false;
    printf("How many elements are there in your list?\n");
    scanf("%d", &n);
    for (int i = 0; i<n; i++){
      scanf("%d", &list[i]);
    }
    printf("What value do you want to find?\n");
    scanf("%d", &valuetofind);
    binary_search();
}
jeff carey

Change

if (n < list[middle] )  q = middle - 1;

to

if (valuetofind < list[middle] )  q = middle - 1;

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related