【转载】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的表示范围,从而使其成为负数。