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

#include 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 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

转载于:https://www.cnblogs.com/lcchuguo/p/4493603.html

你可能感兴趣的:(二分法查找的C语言实现:)