forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearch.java
55 lines (46 loc) · 1.1 KB
/
BinarySearch.java
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
// @saorav21994
// TC : O(logn)
// SC : O(1)
class Solution {
// inbuilt java function
public int search(int[] nums, int target) {
int index = Arrays.binarySearch(nums, target);
if (index < 0) {
return -1;
}
return index;
}
// normal binary search algorithm
public int search(int[] nums, int target) {
int s = 0, e = nums.length - 1;
while (s <= e) {
int mid = s + (e-s)/2;
if (nums[mid] == target)
return mid;
if (nums[mid] < target) {
s += 1;
}
else
e -= 1;
}
return -1;
}
}
// Author: Shobhit Behl (LC: shobhitbruh)
class Solution {
public int search(int[] nums, int target) {
int i=0;
int j=nums.length-1;
while(i<=j){
int m=(i+j)/2;
if(nums[m]==target){
return m;
}else if(nums[m]>target){
j=m-1;
}else{
i=m+1;
}
}
return -1;
}
}