Created
January 16, 2016 23:45
-
-
Save billykwok/df8d8bd96d50d223febf to your computer and use it in GitHub Desktop.
O(n) algorithm to find min and max
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
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