-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Search.cpp
More file actions
60 lines (50 loc) · 1.51 KB
/
Binary Search.cpp
File metadata and controls
60 lines (50 loc) · 1.51 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
57
58
59
60
// Use-of: Binary Search
// 1. https://codeforces.com/edu/course/2/lesson/6/1/practice/contest/283911/problem/A
// 2. https://codeforces.com/edu/course/2/lesson/6/1/practice/contest/283911/problem/B
// 3. https://codeforces.com/edu/course/2/lesson/6/1/practice/contest/283911/problem/C
// 4. https://codeforces.com/edu/course/2/lesson/6/1/practice/contest/283911/problem/D
int binarySearch(int array[], int arraySize, int target) {
int low = 0;
int high = arraySize - 1;
int index = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (array[mid] == target) index = mid;
else if (array[mid] < target) low = mid + 1;
else high = mid - 1;
if (array[mid] == target) break;
}
return index;
}
// Key-point: Maximum index of an array element not greater than the target!
int closestToLeft(int array[], int arraySize, int target) {
int low = 0;
int high = arraySize - 1;
int index = -1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (array[mid] <= target) {
index = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return index;
}
// Key-point: Minimum index of an array element not less than the target!
int closestToRight(int array[], int arraySize, int target) {
int low = 0;
int high = arraySize - 1;
int index = arraySize;
while (low <= high) {
int mid = low + (high - low) / 2;
if (array[mid] >= target) {
index = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return index + 1;
}