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
47
48
|
#include <stdio.h>
#define SIZE 10
int binary_search(int sorted_list[], int low, int high, int element);
int main()
{
int a[ SIZE ] = { 1,2,3,4,5,6,7,8,9,10 };
int e, i, p;
printf("Array:");
for (i=0; i< SIZE ;i++)
{
printf("%d ", a[i]);
}
printf("\n");
printf("please input a integer:");
scanf("%d", &e);
p = binary_search(a, 0, SIZE, e);
if(p >= 0)
{
printf("The key %d was found at %d\n", e, p);
}
else
{
printf("The key %d was not found\n", e);
}
return 0;
}
int binary_search(int sorted_list[], int low, int high, int element)
{
int middle;
while(low <= high)
{
middle = (high-low)/2 +low;
if(element < sorted_list[middle])
high = middle - 1;
else if( element > sorted_list[middle])
low = middle + 1;
else
return middle;
}
return -1;
}
|