Skip to content

Instantly share code, notes, and snippets.

@woonketwong
Created February 19, 2014 00:35
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 woonketwong/9083730 to your computer and use it in GitHub Desktop.
Save woonketwong/9083730 to your computer and use it in GitHub Desktop.
Suppose we are given an array A[1 .. n] with the special property that A[1] ≥ A[2] and A[n − 1] ≤ A[n]. We say that an element A[x] is a local minimum if it is less than or equal to both its neighbors, or more formally, if A[x − 1] ≥ A[x] and A[x] ≤ A[x + 1]. For example, there are five local minima in the following array: 9 7 7 2 1 3 7 5 4 7 3 3…
function findLocalMin(array, start, end){
var mid = Math.floor( (start + end)/2 );
if (((mid - 1) < 0) || ((mid + 1) >= array.length)) return null;
if (array[mid - 2] > array[mid - 1] && array[mid - 1] < array[mid]){
return array[mid-1];
} else if ( (array[mid-1] >= array[mid-2])){
return findLocalMin(array, start, mid);
} else {
return findLocalMin(array, mid, end);
}
}
// var array = [9, -1, 6, 5, 4, 3, 10, 2, 1];
// var array = [5,2,3,4,5,6,7,-1,9];
// console.log("result:", findLocalMin(array, 0, array.length-1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment