时光飞逝~

二分查找
 1 //算法
 2 //1 找中值
 3 //2 将要找的数和中值进行比较,
 4 //    如果大于中值,则从右边的序列找,调用递归
 5 //    如果要找的数小于中值,则从左边的序列找,调用递归
 6 //    如果相等,找到
 7 //    如果没找到,返回-1
 8 
 9 #include "stdio.h"
10 //二分查找
11 int BinaryFind(int *a, int nLen,int data)
12 {
13     int nLeft = 0;
14     int nRight = nLen-1;
15     int mid = (nLeft+nRight)/2;
16     if(data>a[mid])
17         BinaryFind(a,mid+1,nRight);
18     else if(data<a[mid])
19         BinaryFind(a,nLeft,mid-1);
20     else
21         return mid;
22     return -1;
23 }
24 //测试用例
25 int main(int argc, char* argv[])
26 {
27     int a[10]={1,2,3,4,5,6,7,8,9};
28     int nIndex = BinaryFind(a,10,5);
29     printf("%d\n",nIndex);
30     return 0;
31 }
View Code

 

posted on 2013-07-13 21:50  时光飞逝~  阅读(128)  评论(0)    收藏  举报