Last active
March 27, 2017 11:43
-
-
Save ltfschoen/209c2a50781a639850b651bb927ee2df to your computer and use it in GitHub Desktop.
Find Min Value of Rotated Sorted Array
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
/** | |
* Given a sorted array as input (ascending order only | |
* and without duplicates) that may be rotated | |
* and return the minimum value. | |
*/ | |
let getMin = (x, y) => { return x <= y ? x : y; } | |
let getMid = (l, h) => { return parseInt((l + h)/2, 10); } | |
/** | |
* Base case of divide and conquer constrains search | |
* to unsorted sub-array housing the minimum value, | |
* and iteratively selects and processes the next sub-array | |
* until return answer | |
*/ | |
let findMin = (arr, l, h) => { | |
while (arr[l] > arr[h]) { | |
let mid = getMid(l, h); | |
if (arr[mid] > arr[h]) { l = mid + 1 }; | |
if (arr[mid] <= arr[h]) { h = mid }; | |
} | |
return arr[l]; | |
} | |
let input = [2,3,4,-2,-1,0,1], // input | |
l = 0, // lower index | |
h = input.length - 1, // upper index | |
output = findMin(input, l, h); | |
console.log(output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment