首页 > 代码库 > 二分排序之三行代码

二分排序之三行代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#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;