Skip to content

Instantly share code, notes, and snippets.

@connorrose
Created July 11, 2020 15:45
Show Gist options
  • Save connorrose/e29ff5856158e505f674a352ece159e8 to your computer and use it in GitHub Desktop.
Save connorrose/e29ff5856158e505f674a352ece159e8 to your computer and use it in GitHub Desktop.
Rotated Array Search
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