-
Notifications
You must be signed in to change notification settings - Fork 0
/
binsearch.c
50 lines (37 loc) · 813 Bytes
/
binsearch.c
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
49
#include <stdio.h>
#define MAX_LEN 0x1EFFFF
#define TO_FIND 234568
int binsearch(int a[], int n, int x);
void inita(int a[]);
int main()
{
int a[MAX_LEN];
inita(a);
int find;
printf("Index of %d in array is : %d\n", TO_FIND, find = binsearch(a, MAX_LEN, TO_FIND));
printf("Test > a[%d] = %d\n", find, a[find]);
}
void inita(int a[])
{
int gap = 2;
for (int i = 0; i < MAX_LEN; i++)
a[i] = i * gap;
}
int binsearch(int v[], int n, int x)
{
int low, high, mid;
low = 0;
high = n - 1;
mid = (low + high) / 2;
for (; mid > 0; mid = (low + high) / 2) {
if (x > v[mid]) {
low = mid + 1;
}
else if (x < v[mid]) {
high = mid - 1;
}
else
return mid;
}
return -1;
}