二分查找----第一种(相同元素返回不确定哪个)

 1 /*
 2  *binary search 
 3  *just return a value position equals the find but may not the first one
 4  *we should caution the left open right close or left close and right close rules to not happen the boundary error
 5  */
 6 
 7 #include <stdio.h>
 8 #include <stdlib.h>
 9 #include <string.h>
10 
11 /*
12  *binary search
13  *return -1 can not find the number else the position of the number
14  */
15 
16 int binary_search(int in_arr[],int n,int value)
17 {
18     int left,right,middle;
19     left = 0,right = n - 1;
20 
21     while(left <= right)
22     {
23         middle = left + (right - left) / 2; //can solve the number overflow error
24         
25         if(value > in_arr[middle])
26         {
27             left = middle + 1;
28         }
29         else if(value < in_arr[middle])
30         {
31             right = middle - 1;
32         }
33         else
34         {
35             return middle;
36         }
37     }
38 
39     return -1;
40 }
41 
42 int main()
43 {
44     int i,value,in_arr[10];
45 
46     for(i = 0; i < 10; i++)
47     {
48         scanf("%d",&in_arr[i]);
49     }
50     
51     while(1)
52     {
53         printf("input the value to find\n");
54 
55         scanf("%d",&value);
56 
57         int index = binary_search(in_arr,10,value);
58 
59         if(index == -1)
60         {
61             printf("can not find the number %d \n",value);
62         }
63         else
64         {
65             printf("the value %d is at the position %d\n",value,index);
66         }
67     }
68 }

 

posted @ 2015-10-27 16:11  代码的搬运工  阅读(212)  评论(0编辑  收藏  举报