forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Search.cpp
117 lines (95 loc) · 2.09 KB
/
Binary_Search.cpp
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <iostream>
using namespace std;
// Function for binary search
int binarySearch(int array[], int size, int desired)
{
int left = 0, right = size - 1, middle;
while (left <= right)
{
middle = left + (right - left) / 2;
if (array[middle] == desired)
return middle;
else if (desired < array[middle])
right = middle - 1;
else
left = middle + 1;
}
return -1;
}
// Function for lower bound:
// finds the position of the lowest number greater than or equal to desired
int lowerBound(int array[], int size, int desired)
{
int left = -1, right = size, middle;
while (right - left > 1)
{
middle = left + (right - left) / 2;
if (array[middle] < desired)
left = middle;
else
right = middle;
}
return right;
}
// Function for upper bound:
// finds the position of the lowest number strictly greater than desired
int upperBound(int array[], int size, int desired)
{
int left = -1, right = size, middle;
while (right - left > 1)
{
middle = left + (right - left) / 2;
if (array[middle] <= desired)
left = middle;
else
right = middle;
}
return right;
}
// Driver Function
int main()
{
int num;
scanf("%d", &num);
int array[num];
for (int i = 0; i < num; i++) {
scanf("%d", &array[i]);
}
int desired;
scanf("%d", &desired);
if (binarySearch(array, num, desired) != -1)
cout << "Found" << endl;
else
cout << "Not Found" << endl;
// Element greater than or equal than 5
cout << lowerBound(array, num, 5) << endl;
// Element greater than or equal than 6
cout << lowerBound(array, num, 6) << endl;
// Element greater than 5
cout << upperBound(array, num, 5) << endl;
// Element greater than 0
cout << upperBound(array, num, 0) << endl;
return 0;
}
/*
Input:
num = 7
array = {1, 2, 3, 4, 5, 6, 7}
desired = 4
Output:
Found
4
6
6
0
Input:
num = 5
array = {1, 3, 5, 7, 9}
desired = 2
Output:
Not Found
2
3
3
0
*/