Skip to content

Commit c2a3380

Browse files
completed 04-binarySearch/searchInRotatedSortedArray
1 parent f067535 commit c2a3380

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
function search(nums: number[], target: number): number {
2+
// Set the pointers
3+
let lo = 0;
4+
let hi = nums.length - 1;
5+
6+
// Loop until the pointers cross each other.
7+
while (lo <= hi) {
8+
let mid = Math.trunc(lo + (hi - lo) / 2);
9+
10+
if (target === nums[mid]) return mid; // If we've found the value, return.
11+
12+
// Left portion is properly sorted
13+
if (nums[lo]! <= nums[mid]!) {
14+
// Search rightwards if target less than leftmost or greater than mid.
15+
if (target > nums[mid]! || target < nums[lo]!) lo = mid + 1;
16+
// Search leftwards if target more than rightmost or less than mid.
17+
else hi = mid - 1;
18+
}
19+
20+
// Right portion is properly sorted
21+
else {
22+
// Search leftwards if target more than rightmost or less than mid.
23+
if (target < nums[mid]! || target > nums[hi]!) hi = mid - 1;
24+
// Search rightwards if target less than leftmost or greater than mid.
25+
else lo = mid + 1;
26+
}
27+
}
28+
29+
return -1;
30+
}
31+
32+
const input = [4, 5, 6, 7, 0, 1, 2];
33+
const target = 2;
34+
35+
console.log(search(input, target));

0 commit comments

Comments
 (0)