-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearch.cpp
69 lines (53 loc) · 1.16 KB
/
BinarySearch.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
#include<iostream>
using namespace std;
int BinarySearch(int arr[], int size, int key) {
int start = 0;
int end = size - 1;
int mid = (start + end) / 2;
while (start <= end)
{
if (key == arr[mid])
{
return mid;
}
//GO IN RIGHT PART
if (key > arr[mid]) {
start = mid + 1;
}
else {
//if key is less than arr[i]
//then we need to search in left part
end = mid - 1;
}
//Updating Our Mid because Start and end will be updated
mid = (start + end) / 2;
}
return -1;
}
int main()
{
int arr[40];
int size = 0;
cout << "Enter Size Of Array" << endl;
cin >> size;
cout << "Enter " << size << " Elements in Array" << endl;
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
cout << "Your Current Array is" << endl;
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
int key = 0;
cout << "Enter Value you want to find in your array" << endl;
cin >> key;
int Find = BinarySearch(arr, size, key);
if (Find == -1) {
cout << "Value Not found on any index" << endl;
}
else
{
cout << "Value Found on index " << Find << endl;
}
return 0;
}