Last active
October 2, 2018 14:00
-
-
Save sjukkola/ac3bd4f9ca502b9a00291554ee982126 to your computer and use it in GitHub Desktop.
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
/* | |
This problem was asked by Apple. | |
A fixed point in an array is an element whose value is equal to its index. Given a sorted array of distinct elements, return a fixed point, if one exists. Otherwise, return False. | |
For example, given [-6, 0, 2, 40], you should return 2. Given [1, 5, 7, 8], you should return False. | |
check these for better implementation | |
https://rosettacode.org/wiki/Binary_search#JavaScript | |
https://techfindings.one/archives/2964 | |
*/ | |
const arr_1 = [-6, 0, 2, 40]; | |
const arr_2 = [1, 5, 7, 8]; | |
const arr_3 = [-10, -1, 0, 3 , 10, 11, 30, 50, 100] | |
const fixedPointLinear = (array) => { | |
for (i in arr_1) { | |
if (i == array[i]) { | |
return i; | |
} | |
} | |
return -1; | |
} | |
const fixedPoint = (array, low = 0, high = array.length - 1) => { | |
/* pffffff */ | |
const mid = Math.floor((low + high) / 2); | |
if (high >= low) { | |
if(mid == array[mid]) { | |
return array[mid]; | |
} else if (mid > array[mid]) { | |
return fixedPoint(array, mid + 1, high) | |
} else { | |
return fixedPoint(array, low, mid -1); | |
} | |
} | |
return -1; | |
} | |
console.log(fixedPoint(arr_1)); | |
console.log(fixedPoint(arr_2)); | |
console.log(fixedPoint(arr_3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment