来源:http://blog.csdn.net/zzran/article/details/8160103
算法要求在五行之内写出二分查找,我用了6行,不知道有高手可以用五行写出来不:
- #include<stdio.h>
- #include<stdlib.h>
- int a[]={10,22,42,51,56,63,78,99,102,118};
- int binary_search(int low, int high, int key) {
- if(low > high)
- return -1;
- int mid = low + (high - low) / 2;
- if(a[mid] == key)
- return mid;
- return (a[mid] > key ? binary_search(low, mid-1, key) : binary_search(mid+1, high, key));
- }
- void main() {
- int result = binary_search(0, sizeof(a)/sizeof(int), 102);
- printf("%d\n",a[result]);
- }
注意 int mid = low + (high - low) / 2;这句,很多面试题目都有这个问题,这个主要是编程的细节问题,开始可能想到这样写:int mid = (low + high) / 2;但是 low,和high的值加起来之后有可能超出int的表示范围,从而使其成为负数。
==============评论里有人写:
- int binSearch(int* a, int begin, int end, int k){
- int mid = begin + ( (end - begin)>>1 ),index;
- index = a[mid] < k && begin + 1 < end ? binSearch(a,mid+1,end,k) :
- ( a[mid] > k && begin + 1 < end ? binSearch(a,begin,mid,k) :
- mid * (a[mid] == k) + (a[mid] != k)*(-1));
- return index;
- }