-
Notifications
You must be signed in to change notification settings - Fork 0
/
search-in-rotated-sorted-array.js
75 lines (54 loc) · 1.64 KB
/
search-in-rotated-sorted-array.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function (nums, target) {
// Special case
if (nums === null || nums.length === 0) {
return -1;
}
// Left and right pointers in the array
let left = 0;
let right = nums.length - 1;
// First step is to find the pivot where the
// array is rotated
while (left < right) {
// Middle pointer
let middle = left + parseInt((right - left) / 2);
// If the element at the mid is greater than
// the element at the right then we can say that
// the array is rotated after middle index
if (nums[middle] > nums[right]) {
left = middle + 1;
}
// Else, the pivot is in the left part
else {
right = middle;
}
}
// After the above loop is completed, then the
// left index will point to the pivot
const pivot = left;
left = 0;
right = nums.length - 1;
// Now we will find in which half of the array,
// our target is present
if (target >= nums[pivot] && target <= nums[right]) {
left = pivot;
} else {
right = pivot;
}
// Now perform normal binary search
while (left <= right) {
let middle = left + parseInt((right - left) / 2);
if (nums[middle] === target) {
return middle;
} else if (target < nums[middle]) {
right = middle - 1;
} else {
left = middle + 1;
}
}
return -1;
};