Skip to content

Instantly share code, notes, and snippets.

@ltfschoen
Last active March 27, 2017 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ltfschoen/209c2a50781a639850b651bb927ee2df to your computer and use it in GitHub Desktop.
Save ltfschoen/209c2a50781a639850b651bb927ee2df to your computer and use it in GitHub Desktop.
Find Min Value of Rotated Sorted Array
/**
* 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