forked from wzqnls/The-C-Programming-Language-Exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3-1.c
More file actions
42 lines (34 loc) · 793 Bytes
/
3-1.c
File metadata and controls
42 lines (34 loc) · 793 Bytes
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
/*
* Our binary search makes two tests inside the loop, when one would suffice (at
* the price of more tests outside.) Write a version with only one test inside the loop and
* measure the difference in run-time.
* */
#include <stdio.h>
int binsearch(int x, int v[], int n);
int main()
{
int x = 10;
int v[] = {1, 2, 3, 4, 10, 11, 15};
int n = 7;
printf("%d\n", binsearch(x, v, n));
return 0;
}
int binsearch(int x, int v[], int n)
{
int low, high, mid;
low = 0;
high = n - 1;
mid = (low + high) / 2;
while(low <= high && x != v[mid])
{
if (x < v[mid])
high = mid - 1;
else
low = mid + 1;
mid = (low + high) / 2;
}
if (x == v[mid])
return mid;
else
return -1;
}