二分法查找的C语言实现:

#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

你可能感兴趣的:(c,测试,ini,语言,include)