2015-11-05 162 views
1

我的二進制搜索程序編譯,但我的算法出了問題。例如,如果我嘗試在列表中找到9 5 7 8 9 10,我的程序說列表中沒有9。我哪裏錯了?C二進制搜索

#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(); 
} 

回答

3

變化

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

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