折半查找

有一个数组A[10],里面存放了10个整数,顺序递增,A[10]={2,3,5,7,8,10,12,15,19,21},任意输入一个数字n,用折半查找法找到n位于数组中的位置,如果n不属于数组A,显示错误提示

算法分析:折半查找 代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <stdio.h>

int bin_search(int A[], int n, int key)
{
int mid,high,low;
low = 0;
high = n-1;
while(low<=high)
{
mid=(high+low)/2;
if(a[mid]==key)
{
return mid;
}
if(a[mid]>key)
{
high=mid-1;
}
if(a[mid]<key)
{
low=mid+1;
}
}
return -1;
}

int main()
{
int A[10] = {2,3,5,7,8,10,12,15,19,21}
int i,n,addr;
printf("The contents of the Array A[10] are\n");
for(i=0;i<10;i++)
{
printf("%d ", A[i]);
}
printf("\nPlease input a interger for search\n");
scanf("%d",&n);
addr = bin_search(A,10,n);
if(addr != -1)
{
printf("%d is at the %dth unit is array A\n ",n,addr);
}
else
{
printf("There is no %d in array A\n",n);
}

If you like my blog, please donate for me.