Binarysearch

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
#include<stdio.h>
#include<malloc.h>
int Binsearch(int a[],int N,int whichnumber)
{
int low, high, mid,j;
j = -1;
low = 0;
high = N-1;
while ((low <= high)&&(j == -1))
{
mid = (low + high)/2;
if (a[mid] == whichnumber) j = mid+1;
else if (a[mid] > whichnumber) high = mid - 1;
else low = mid + 1;
}
return j;
}
int main()
{
int N,M;
int *a;
char *b;
int i;
printf("Please input the number of the array : ");
scanf("%d ",&N);
a = (int*)malloc(N*sizeof(int));
for (i = 0; i < N; i++)
scanf("%d", &a[i]);

int where,whichnumber;
printf("Please input which number would you want to find :");
scanf("%d", &whichnumber);
where = Binsearch(a, N, whichnumber);
if (where==-1)
{
printf("error!");
}
else
printf("%d",where);
}
------ 本文结束------
坚持原创技术分享,您的支持将鼓励我继续创作!

欢迎关注我的其它发布渠道