Skip to content

Instantly share code, notes, and snippets.

@billykwok
Created January 16, 2016 23:45
Show Gist options
  • Save billykwok/df8d8bd96d50d223febf to your computer and use it in GitHub Desktop.
Save billykwok/df8d8bd96d50d223febf to your computer and use it in GitHub Desktop.
O(n) algorithm to find min and max
function minMax(array) {
if (array.length <= 1) {
return [ array[0], array[0] ];
} else if (array.length == 2) {
return array[0] < array[1] ? [ array[0], array[1] ] : [ array[1], array[0] ];
} else {
const breakpt = array.length / 2;
const [ minLeft, maxLeft ] = minMax(array.slice(0, Math.floor(breakpt)));
const [ minRight, maxRight ] = minMax(array.slice(Math.floor(breakpt)));
return [ minLeft < minRight ? minLeft : minRight,
maxLeft > maxRight ? maxLeft : maxRight ];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment