Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Last active July 2, 2019 06:24
Show Gist options
  • Select an option

  • Save anushshukla/067f7079ea1da6f1acf3e89223744d1c to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/067f7079ea1da6f1acf3e89223744d1c to your computer and use it in GitHub Desktop.
Matching Ranges for a certain value
const sample = [1, 6, 4, 10, 27, 15, 120, 25, 222, 30];
const sampl2 = [1, 6, 4, 10, 27, 15, 20, 25, 22, 30];
const isEven = integer => integer % 2 === 0;
const findValueFromAlternateSortedArray = (arr, search, prevIndex = 0) => {
const arrLen = arr.length - 1;
const pivotIndex = Math.floor(arrLen / 2);
const nextPivotIndex = isEven(arrLen) ? pivotIndex : pivotIndex + 1;
const pivotIndexValue = arr[pivotIndex];
const nextPivotIndexValue = arr[nextPivotIndex];
if (search === pivotIndexValue) {
return pivotIndex;
}
if (search === nextPivotIndexValue) {
return nextPivotIndex;
}
if (search < nextPivotIndexValue) {
const leftHalf = arr.slice(0,pivotIndex);
const index = findValueFromAlternateSortedArray(leftHalf, search);
if (index !== -1) {
return index;
}
}
if (search > pivotIndexValue) {
const rightHalf = arr.slice(nextPivotIndex);
console.log(nextPivotIndex, prevIndex);
const index = findValueFromAlternateSortedArray(rightHalf, search, nextPivotIndex + prevIndex);
console.log(index);
return index + prevIndex;
}
return -1;
}
console.log(findValueFromAlternateSortedArray(sampl2, 30));
// console.log(findValueFromAlternateSortedArray(sampl2, 1));
// console.log(findValueFromAlternateSortedArray(sampl2, 4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment