-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask1solution.c
More file actions
56 lines (50 loc) · 1.44 KB
/
Copy pathtask1solution.c
File metadata and controls
56 lines (50 loc) · 1.44 KB
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
50
51
52
53
54
55
56
#include <stdio.h>
#include <time.h> // measuring run time
int A[100000000];
int linear_search(int A[], int n, int t) {
for(int i = 0; i < n; i++) {
if (A[i] == t) {
return 1; // found in the array
}
}
return 0; // not found
}
int binary_search(int A[], int n, int t) {
int l = 0, r = n - 1;
int mid;
while (l <= r) {
mid = (int)((r - l) / 2 + l);
// printf("%d\n", mid);
if (A[mid] == t) {
return 1; // found in the array
} else if(A[mid] > t) {
r = mid - 1;
} else {
l = mid + 1;
}
}
return 0; // not found
}
int main() {
int n, t;
clock_t start, end;
n = 100000000;
t = 100000000;
printf("Generate an array with %d distinct integers from 1 to %d.\n", n, n);
for(int i = 0; i < n; i++) A[i] = i + 1;
int count = 100;
start = clock();
for(int c = 1; c <= count; c++) {
linear_search(A, n, t); // complete your implementation
}
end = clock();
double run_time = ((double)(end - start))/(CLOCKS_PER_SEC/1000);
printf("Linear search takes : %f millseconds\n", run_time / count);
start = clock();
for(int c = 1; c <= count; c++) {
binary_search(A, n, t); // complete your implementation
}
end = clock();
run_time = ((double)(end - start))/(CLOCKS_PER_SEC/1000);
printf("Binary search takes : %f millseconds\n", run_time / count);
}