-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary Search.cpp
55 lines (44 loc) · 1.28 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
// Binary Search
// Difficulty: BasicAccuracy: 44.32%Submissions: 486K+Points: 1
// Given a sorted array of size N and an integer K, find the position(0-based indexing) at which K is present in the array using binary search.
// Example 1:
// Input:
// N = 5
// arr[] = {1 2 3 4 5}
// K = 4
// Output: 3
// Explanation: 4 appears at index 3.
// Example 2:
// Input:
// N = 5
// arr[] = {11 22 33 44 55}
// K = 445
// Output: -1
// Explanation: 445 is not present.
// Your Task:
// You dont need to read input or print anything. Complete the function binarysearch() which takes arr[], N and K as input parameters and returns the index of K in the array. If K is not present in the array, return -1.
// Expected Time Complexity: O(LogN)
// Expected Auxiliary Space: O(LogN) if solving recursively and O(1) otherwise.
// Constraints:
// 1 <= N <= 105
// 1 <= arr[i] <= 106
// 1 <= K <= 106
class Solution {
public:
int binarysearch(int arr[], int n, int k) {
// code here
int low=0;
int high=n-1;
while(low<=high){
int mid=(low+high)/2;
if(arr[mid]==k){
return mid;
}else if(arr[mid]>k){
high=mid-1;
}else{
low=mid+1;
}
}
return -1;
}
};