forked from super30admin/Binary-Search-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearch_InRotated_sorted_Array.java
More file actions
55 lines (47 loc) · 1.81 KB
/
Search_InRotated_sorted_Array.java
File metadata and controls
55 lines (47 loc) · 1.81 KB
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
/*
Time Complexity :
O(log(n)) because in each iteration we will reduce the input size by half (avoiding the other half because element is not in that half)
Space Complexity :
O(1) we are not using any auxilary space
Did this code successfully run on Leetcode : YES
Any problem you faced while coding this :
Handling edge case was tricky
*/
public class Search_InRotated_sorted_Array {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length-1;
while( left <= right){
int mid = (left +right)/2;
if (nums[mid] == target) {return mid;}
// if left array is sorted
if( nums[left]<= nums[mid] ){
// if array is in left sorted array search in left side so change right to mid-1
if(target <= nums[mid] && target >= nums[left]){
right = mid-1;
}else{
// else element is in right side of array update the left = mid+1
left = mid + 1;
}
}
// if right array is sorted
else{
// if element is in right sorted array
if ( target >= nums[mid] && target <= nums[right]){
left = mid + 1;
}else{
// else element is in left side of array
right = mid -1;
}
}
}
return -1;
}
public static void main(String[] args) {
Search_InRotated_sorted_Array obj = new Search_InRotated_sorted_Array();
int arr []={4,5,6,7,0,1,2};
int target = 4;
int index = obj.search(arr, target);
System.out.println("index"+index);
}
}