-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.cpp
More file actions
43 lines (34 loc) · 971 Bytes
/
binary_search.cpp
File metadata and controls
43 lines (34 loc) · 971 Bytes
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
/******************************************************************************
*******************************************************************************/
#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int c){
int low = 0;
int high = n - 1;
while(low <= high){
int mid = (low + high) / 2;
if(c == arr[mid]){
return mid;
}else if(c < arr[mid]){
high = mid - 1;
}else{
low = mid + 1;
}
}
return -1;
}
int main()
{
int toSearch;
cout << "Enter number to search: ";
cin >> toSearch;
int arr[] = {12, 45, 2, 23, 2, 10};
int size = sizeof(arr) / sizeof(arr[0]);
int index = binarySearch(arr, size, toSearch);
if(index != -1){
cout << toSearch << " found at index " << index << endl;
}else{
cout << "Oops not able to find " << toSearch << " in array";
}
return 0;
}