You don't need to sort it, just search linearly for the two largest:
EDIT: The code below should work asymptotically faster than the OP code. First, the OP performs sorting, which can be done in O (n log n), assuming a random list. My code does a linear list search in O(cn) using c = 2 (two loops are optional but simple). The solution for ceil(n log n) = 2n with n positive integer is 14, that is, for each list longer than 14 entries, the code below is faster. For example: per million records, the ratio is 13,815,511 to 2,000,000, which is more than six times faster. You can do the same in a single loop that shortens the execution time (theoretically, but it is also slightly faster due to better locality).
function maxtwo_wrong(a){ var b1 = -Infinity; var b2 = -Infinity; for (var i=0; i < a.length; i++) { if (a[i] > b1) { b1 = a[i]; } } for (var i=0; i < a.length; i++) { if (a[i] > b2 && a[i] < b1) { b2 = a[i]; } } return [b1,b2]; }
EDIT-2: the code above maxtwo_wrong does not seem to meet the requirements, so I wrote another maxtwo_right and put it below. Please OP, tell me which one meets your requirements so that I can remove the wrong one.
EDIT-3: simplified and fixed.
function maxtwo_right(a){ var b1 = -Infinity; var b2 = -Infinity; for (var i=0; i < a.length; i++) {
deamentiaemundi
source share