Created
July 11, 2020 15:45
-
-
Save connorrose/e29ff5856158e505f674a352ece159e8 to your computer and use it in GitHub Desktop.
Rotated Array Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const search = function pivotSearch(nums, target) { | |
// track sub array start & end | |
let leftIdx = 0; | |
let rightIdx = nums.length - 1; | |
while (rightIdx >= leftIdx) { | |
const midIdx = ((rightIdx + leftIdx) / 2) | 0; | |
const midNum = nums[midIdx]; | |
if (target === midNum) return midIdx; | |
const rightNum = nums[rightIdx]; | |
const pivotRight = rightNum - midNum < 0; | |
if ( | |
(pivotRight && (target <= rightNum || target >= midNum)) | |
|| (!pivotRight && target <= rightNum && target >= midNum) | |
) { | |
// search right half | |
leftIdx = midIdx + 1; | |
} else { | |
// search left half | |
rightIdx = midIdx - 1; | |
} | |
} | |
return -1; | |
}; | |
// target = 1; | |
// [6, 7, 0, 2, 3, 4, 5]; | |
// [3, 4, 5, 6, 7, 0, 2]; | |
const testArr = [4, 5, 6, 7, 0, 1, 2]; | |
// const testArr = [0, 2]; | |
console.log(search(testArr, 6)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment