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

本文介绍了一种二分查找算法的实现方式,并提供了完整的C语言代码示例。该算法能够在一个有序数组中查找指定数值的位置,若未找到则返回-1。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值