Select question-Determine the top K maximum in N number

Source: Internet
Author: User

Algorithm: The first k elements are read into the array and sorted, the remaining elements are read one by one, and when the new element is less than the K element in the array is ignored, otherwise it is placed in the correct position in the array, and an element in the array is extruded into an array.

Code with js!

/*code*/

Window.onload = Entryfun;

Entry function
function Entryfun () {

var sortnumber = new Array (100, 90, 80, 70, 85, 95, 99);

var k = 4;

document.write (Selpro (Sortnumber, k));

}

function Arr_oper (Sortnumber, time) {

for (i = sortnumber.length-1; I >= sortnumber.length-time + 1; i--) {

Sortnumber[i] = sortnumber[i-1];

}

return sortnumber;

}

Quick Sort
function QuickSort (Sortnumber, left, right) {

if (Left > right) {

Return

}

var i = left;

var j = right;

var key = Sortnumber[left];

while (I < j) {

while (I < J && Sortnumber[j] < key) {

j--;

}

Sortnumber[i] = Sortnumber[j];

while (I < J && Sortnumber[i] > key) {

i++;

}

SORTNUMBER[J] = Sortnumber[i];

}

Sortnumber[i] = key;

QuickSort (Sortnumber, left, i-1);

QuickSort (Sortnumber, i + 1, right);

return sortnumber;

}

function Selpro (Sortnumber, k) {

var Rs_arr = quickSort (sortnumber, 0, k-1);

var Sort_arr = Rs_arr.slice (0, k);

var Unsort_arr = Rs_arr.slice (k);

var time = 0;

for (var i = k; I <= sortnumber.length-1; i++) {

Time = 0;

if (Rs_arr[i] < sort_arr[k-1]) {

Continue

}

if (Rs_arr[i] > Sort_arr[0]) {

Time = Sort_arr.length;

Arr_oper (Sort_arr, time);

Sort_arr[0] = Rs_arr[i];

}

else {

for (var j = k-1; J >= 1; j--) {

if (Rs_arr[i] > Sort_arr[j]) {

time++;

}

}

j = sort_arr.length-time;

Window.alert (time);

Window.alert ("j=" + j);

Arr_oper (Sort_arr, time);

SORT_ARR[J] = Rs_arr[i];

return Sort_arr;

}

}

return Sort_arr;

}


Select question-Determine the top K maximum in N number

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.