Returns the largest number of K (JS implementations) in a set of numbers

Source: Internet
Author: User

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.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.