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