Skip to content

Instantly share code, notes, and snippets.

@galenweber
Created April 22, 2016 18:57
Show Gist options
  • Save galenweber/cc806ce24b8927cceffd0e16de3f84dc to your computer and use it in GitHub Desktop.
Save galenweber/cc806ce24b8927cceffd0e16de3f84dc to your computer and use it in GitHub Desktop.
// Given an array of integers, find a peak if it exists
// Where a peak is defined as greater than or equal to previous
// and subsequent values (for edge, >= to sole neighbor)
var isPeak = function(l,m,r) {
if (typeof l === 'undefined') {
return (m>=r)
} else if (typeof r === 'undefined') {
return (m>=l);
} else {
return ((m >= l) && (m >= r));
}
}
var findPeakRecurs = function(array, position = Math.floor(array.length/2)) {
var mid = array[position];
var left = array[position - 1];
var right = array[position + 1];
if (isPeak(left, mid, right)) {
return position;
} else if (left > mid) {
// So look at the mid of the left side
return findPeakRecurs(array, Math.floor(position/2))
} else {
// So look at the mid of the right side
return findPeakRecurs(array, Math.floor(position + (array.length - position)/2))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment