-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.c
63 lines (50 loc) · 1.22 KB
/
BinarySearch.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// impelement binary search in C language
// if we use recursion method
#define E_TARGET_NOT_IN_ARRAY -1
#define E_ARRAY_UNORDERED -2
#define E_LIMITS_REVERSED -3
int BinarySearch(int* array, int lower, int upper, int target)
{
int center, range;
range = upper - lower;
if (range < 0) {
return E_LIMITS_REVERSED;
} else if (range == 0 && array[low] != target) {
return E_TARGET_NOT_IN_ARRAY;
}
if (array[lower] > array[upper]) {
return E_ARRAY_UNORDERED;
}
center = ((range)/2) + lower;
if (target == array[center]) {
return center;
} else if (target < array[center]) {
return BinarySearch(array, lower, center - 1, target);
} else {
return BinarySearch(array, center + 1, upper, target);
}
}
int IterBinarySearch(int* array, int lower, int upper, int target)
{
int center, range;
if (lower > upper) {
return E_LIMITS_REVERSED;
}
while (1) {
range = upper - lower;
if (range == 0 && array[lower] != target) {
return E_TARGET_NOT_IN_ARRAY;
}
if (array[lower] > array[upper]) {
return E_ARRAY_UNORDERED;
}
center = ((range)/2) + lower;
if (target == array[center]) {
return center;
} else if (target < array[center]) {
upper = center - 1;
} else {
lower = center + 1;
}
}
}