forked from souvikg544/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.cpp
More file actions
40 lines (37 loc) · 833 Bytes
/
BinarySearch.cpp
File metadata and controls
40 lines (37 loc) · 833 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
// BINARY SEARCH
/*Problem: Given a sorted array of size n and an integer k,find the position at which k is present in the array using binary search
Time Complexity: O(logn), where n is the size of the input array
Space Complexity: O(1)
*/
#include <bits/stdc++.h>
using namespace std;
int binarysearch(int arr[], int n, int k)
{
int start = 0;
int end = n - 1;
int ans = -1;
while (start <= end)
{
int mid = start + (end - start) / 2;
if (arr[mid] == k)
{
ans = mid;
break;
}
else if (arr[mid] < k)
{
start = mid + 1;
}
else
{
end = mid - 1;
}
}
return ans;
}
int main()
{
int arr[5] = {10, 20, 30, 40, 50};
cout << binarysearch(arr, 5, 40) << endl;
return 0;
}