forked from ankitsamaddar/blind75_cpp_solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16_Binary Search.cpp
48 lines (45 loc) · 928 Bytes
/
16_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
// DATE: 30-06-2023
/* PROGRAM: 16_Binary Search
Enter N elements in an array and enter the key. Find if key is present in the array using Binary Search, if present print the index.
INPUT
10
1 2 3 8 10 15 21 33 41 52
21
OUTPUT
6
EXPLANATION
- searching algorithm used in a sorted array by repeatedly dividing the search interval in half.
- The idea of binary search is to use a sorted array and reduce the time complexity to O(log N).
*/
// @ankitsamaddar @2023
#include <iostream>
using namespace std;
int binarySearch(int n,int arr[],int key){
int s,mid = 0;
int e = n-1;
while(s<=e){
mid = (s+e)/2;
if(arr[mid]==key){
return mid;
}
else if (arr[mid]<key) {
s = mid+1;
}
else{
e = mid -1;
}
}
return -1;
}
int main() {
int n,key;
cin >> n;
int arr[100];
for (int i = 0; i<n; i++) {
cin>>arr[i];
// cout<<arr[i]<<" ";
}
cin>>key;
cout<<binarySearch(n, arr, key);
return 0;
}