#include <stdio.h> int binSearch(int, int, int); main() { int i, n = 10, x = 7; //这里假设把数组a[]定义为a[n],是错误的,不能定义变长数组。 int a[10]; printf("Please enter your num:/n"); //从标准输入给数组赋值的唯一方法:用for循环 for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("The %d can be found in the arr, it is %dth of the arr/n", x, binSearch(x,a,n)); } /*第一种方法,推断都在循环内*/ int binSearch(int x, int a[], int n) { int low, high, mid; low = 0; high = n-1; //注意,这里必须用<=, 用<不正确,一直返回-1 while(low <= high) { mid = (low + high) / 2; if(x < a[mid]) high = mid - 1; else if(x > a[mid]) low = mid + 1; else return mid; } return -1; } /*在循环内运行一次測试的方法*/ /*int binSearch(int x, int a[], int n) { int low, high, mid; low = 0; high = n-1; mid = (low + high) / 2; while((low <= high)&&(a[mid]!=x)) { if(x < a[mid]) high = mid -1; else low = mid + 1; mid = (low + high) / 2; } if(a[mid] == x) return mid; else return -1; } */
时间复杂度 log2n