# 按值查找之折半查找

6 篇文章 0 订阅

#include <iostream>
using namespace std;

int  Binary_find(int *arr,int len,int value)
{
if(NULL==arr||0==len)
{
return -1;
}
int start = 0;
int end = len-1;
while(start<=len)
{
int mid = start+((end-start)>>1);//左移一位相当于除2
if(value==arr[mid])
return arr[mid];
else if(value > arr[mid])
start = mid+1;
else
end=mid-1;
}
return -1;
}

int main()
{
int a[]={0,1,2,3,4,5,6,7,8,9,10,11,15,45,48};
int len=sizeof(a)/sizeof(a[0]);
int b= Binary_find(a,len,45);
cout<<b<<endl;

}


#include <stdio.h>

int bin_search(int key[],int low, int high,int k)

{

int mid;

if(low>high)

return -1;

else{

mid = (low+high) / 2;

if(key[mid]==k)

return mid;

if(k>key[mid])

return bin_search(key,mid+1,high,k);        /*在序列的后半部分查找*/

else

return bin_search(key,low,mid-1,k);            /*在序列的前半部分查找*/

}

}

int main()

{

int n , i , addr;

int A[10] = {2,3,5,7,8,10,12,15,19,21};

printf("The contents of the Array A[10] are\n");

for(i=0;i<10;i++)

printf("%d ",A[i]);                                /*显示数组A中的内容*/

printf("\nPlease input a interger for search\n");

scanf("%d",&n);                                /*输入待查找的元素*/

printf("%d is at the %dth unit is array A\n ",n,addr);

else printf("There is no %d in array A\n",n);            /*查找失败*/

getchar();

return 0;

}



08-08 333
08-30
03-02
08-07
09-21
09-04
03-14 7万+
10-18
10-17
06-14
05-23
05-13
05-22
08-13

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

vim404

¥2 ¥4 ¥6 ¥10 ¥20

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