二分排序之三行代码
#include<stdio.h> #include<stdlib.h> int a[]={10,22,42,51,56,63,78,99,102,118}; 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; } int main() { int result = binSearch(a,0, sizeof(a)/sizeof(int), 22); printf("%d\n",result); return 0; }