Last active
July 3, 2019 01:28
-
-
Save anushshukla/e12ed4ff40af2c41216b2ddb685f2269 to your computer and use it in GitHub Desktop.
Given an array in which elements at odd indices are sorted & elements at even indices are sorted individually. Please write a function to search an element in the array.
This file contains hidden or 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 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 lastIndex = arr.length - 1; | |
| const hasOneValue = arr.length === 1; | |
| const pivotIndex = Math.floor(lastIndex / 2); | |
| const nextPivotIndex = isEven(lastIndex) ? pivotIndex : pivotIndex + 1; | |
| const pivotIndexValue = arr[pivotIndex]; | |
| const nextPivotIndexValue = arr[nextPivotIndex]; | |
| if (search === pivotIndexValue) { | |
| return pivotIndex + prevIndex; | |
| } else if (search === nextPivotIndexValue) { | |
| return nextPivotIndex + prevIndex; | |
| } else if (hasOneValue) { | |
| return -1; | |
| } | |
| if (search < nextPivotIndexValue || search < pivotIndexValue) { ; | |
| const leftHalf = arr.slice(0, pivotIndex); | |
| const index = findValueFromAlternateSortedArray(leftHalf, search); | |
| if (index !== -1) { | |
| return index; | |
| } | |
| } | |
| if (search > pivotIndexValue || search > nextPivotIndexValue) { | |
| const sliceIndex = nextPivotIndex + 1; | |
| const rightHalf = arr.slice(sliceIndex); | |
| const index = findValueFromAlternateSortedArray(rightHalf, search, sliceIndex + prevIndex); | |
| return index; | |
| } | |
| return -1; | |
| } | |
| console.log(findValueFromAlternateSortedArray(sampl2, 30)); // 9 | |
| console.log(findValueFromAlternateSortedArray(sample, 25)); // 7 | |
| console.log(findValueFromAlternateSortedArray(sample, 30)); // 9 | |
| console.log(findValueFromAlternateSortedArray(sampl2, 1)); // 0 | |
| console.log(findValueFromAlternateSortedArray(sampl2, 4)); // 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment