对有序数组{2、11、15、19、30、32、61、72、88、90、96}进行二分查找,则成功找到15需比较()次:
A 3 B 4 C 2 D 5
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int binary_search(int* a, int len, int goal) 5 { 6 int low = 0; 7 int high = len - 1; 8 while(low <= high) 9 { 10 int middle = (low + high)/2; 11 if(a[middle] == goal) 12 return middle; 13 //在左半边 14 else if(a[middle] > goal) 15 high = middle - 1; 16 //在右半边 17 else 18 low = middle + 1; 19 } 20 //没找到 21 return -1; 22 } 23 24 int main(void){ 25 int a[11] = {2,11,15,19,30,32,61,72,88,90,96}; 26 printf("%d ", binary_search(a, 11, 15)); 27 return 0; 28 }
答案是2次