The first time I saw a similar topic was about six years ago. A simple ACM problem, his own half a day to use soil method to obtain results, with others using heap sorting to obtain results of time efficiency difference several times, making the first time I deeply appreciate the charm of the algorithm. Six years later, once again asked the question, "heap sort" instantly jumped into the mind.
The difference is that at that time play C, now play Java and JS, the most familiar is JS, and then use JS to write out the algorithm:
function Topkmaxofarr (k, arr) {function swap (A, b) {var t = arr[a];arr[a] = arr[b];arr[b] = t;} var i,j; Just Loop k times for (i=arr.length;i>arr.length-k;i--) {for (J=math.floor (I/2) -1;j>=0;j--) {if (arr[j]<arr[2*j+1]) { Swap (J, 2*j+1);} if (2*j+2<i && arr[j]<arr[2*j+2]) {swap (J, 2*j+2);}} Swap (i-1, 0);} Return Arr.slice (arr.length-k);} usage example var arr = [4,2,5,6,77,33,21,44,55,22], K=5;topkmaxofarr (k, arr);//return array [22, 33, 44, 55, 77]
welcome criticism.