Skip to content

Commit b4dbed8

Browse files
committed
init chapter3
1 parent 5004937 commit b4dbed8

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

chapter-3-control-flow/1.binsearch.c

+92
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
#include <stdio.h>
2+
#include <time.h>
3+
4+
5+
#define ARRAY_LEN 500000
6+
7+
int binsearch(int, int[], int);
8+
int binsearchFast(int, int[], int);
9+
10+
main()
11+
{
12+
clock_t start, finish;
13+
int i, v[ARRAY_LEN];
14+
for (i = 0; i < ARRAY_LEN; i++)
15+
v[i] = i;
16+
17+
start = clock();
18+
int p;
19+
for (i = 0; i < ARRAY_LEN; i++) {
20+
p = binsearch(i, v, ARRAY_LEN);
21+
//printf("%d at %d\n", i, p);
22+
}
23+
finish = clock();
24+
25+
printf("binsearch duration: %f\n", ((double)(finish - start)) / CLOCKS_PER_SEC);
26+
27+
//printf("binsearchFast:\n");
28+
29+
start = clock();
30+
for (i = 0; i < ARRAY_LEN; i++) {
31+
p = binsearchFast(i, v, ARRAY_LEN);
32+
//printf("%d at %d\n", i, p);
33+
}
34+
finish = clock();
35+
printf("binsearchFast duration: %f\n", ((double)(finish - start)) / CLOCKS_PER_SEC);
36+
37+
for (i = -10000; i < ARRAY_LEN; i++) {
38+
p = binsearchFast(i, v, ARRAY_LEN);
39+
if (i < 0 && p != -1)
40+
break;
41+
else if (i >= 0 && p != i)
42+
break;
43+
}
44+
printf("i: %d\n", i);
45+
}
46+
47+
/* binsearch: find x in v[0] <= v[1] <= ... v[n-1] */
48+
int binsearch(int x, int v[], int n)
49+
{
50+
int low, high, mid;
51+
52+
low = 0;
53+
high = n - 1;
54+
while (low <= high) {
55+
mid = (low + high) / 2;
56+
if (x < v[mid])
57+
high = mid - 1;
58+
else if (x > v[mid])
59+
low = mid + 1;
60+
else
61+
return mid;
62+
}
63+
return -1;
64+
}
65+
66+
int binsearchFast(int x, int v[], int n)
67+
{
68+
int low, high, mid;
69+
70+
low = 0;
71+
high = n - 1;
72+
while (low <= high) {
73+
mid = (low + high) / 2;
74+
75+
if (x <= v[mid])
76+
high = mid - 1;
77+
else
78+
low = mid + 1;
79+
}
80+
81+
if (x == v[mid])
82+
return mid;
83+
else if (x > v[mid])
84+
mid += 1;
85+
else
86+
mid -= 1;
87+
88+
if (mid < 0 || mid > n - 1)
89+
return -1;
90+
else
91+
return mid;
92+
}

0 commit comments

Comments
 (0)