forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_Search.cpp
63 lines (52 loc) · 1.56 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
/**
* copyright 2020 @author omkarlanghe
* @file
* Implementation of Binary search algorithm.
*/
#include <iostream>
#include <algorithm>
bool binary_search(int *, int, int, int);
/**
* Function which returns true if element found in an array, else returns false.
*/
bool binary_search(int *arr, int search_element, int lb, int ub) {
while (lb <= ub) {
int mid = ((lb + ub) / 2);
if (arr[mid] == search_element) {
return (true);
} else if (arr[mid] > search_element) {
ub = mid - 1;
} else {
lb = mid + 1;
}
}
return (false);
}
/** Main function */
int main() {
int t, n, search_element;
int *arr = nullptr;
std::cout << "Enter the number of test cases : " << std::endl;
std::cin >> t;
while (t--) {
std::cout << "Enter the size of an array : " << std::endl;
std::cin >> n;
arr = new int[n]; // dynamic memory allocation
std::cout << "Enter the elements in an array : " << std::endl;
for (int i = 0 ; i < n ; i++) {
std::cin >> arr[i];
}
std::sort(arr, arr + n);
std::cout << "Enter the element to search : " << std::endl;
std::cin >> search_element;
// call to binary search function
bool result = binary_search(arr, search_element, 0, n);
if(result) {
std::cout << "Element found." << std::endl;
} else {
std::cout << "Element not found." << std::endl;
}
delete[] arr; // free memory after use
}
return 0;
}