算法:前K元素读入数组并对其排序,将剩下的元素再逐个读入,当新元素小于数组中第k个元素则忽略,否则将其放到数组中正确位置上,同时将数组中的一个元素挤出数组。
代码采用JS!
/*Code*/
window.onload = entryFun;
//入口函数
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;
}
// 快速排序
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;
}