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
57
58
59
60
61
|
#include <stdio.h>
#include <math.h>
int
linear(int *haystack, int len, int needle)
{
for (int i = 0; i < len; ++i) {
if (haystack[i] == needle) {
return 1;
}
}
return 0;
}
int
binary(int *haystack, int low, int high, int needle)
{
if (low > high) {
return 0;
}
int mid = low + (high - low) / 2;
if (haystack[mid] == needle) {
return 1;
} else if (haystack[mid] > needle) {
binary(haystack, low, mid - 1, needle);
} else {
binary(haystack, mid + 1, high, needle);
}
}
int
square(int *breaks, int len, int needle)
{
int jmp = floor(sqrt(len));
int i = jmp;
for (; i < len; i += jmp){
if (breaks[i]) {
break;
}
}
i -= jmp;
for (int j = 0; j <= jmp && i < len; ++i, ++j) {
if (breaks[i]) {
return i;
}
}
return 0;
}
int
main()
{
int haystack[5] = {0, 1, 2, 3, 4};
int breaks[5] = {0, 0, 1, 0, 0};
int len = sizeof(haystack) / sizeof(int);
printf("%d\n", linear(haystack, len, 3));
printf("%d\n", binary(haystack, 0, len, 3));
printf("%d\n", square(breaks, len, 3));
return 0;
}
|