如何在保持原始排序的同时获取数组中N个最高数字?
问题描述:
例如,对于N个最高的数字,可以说N = 3如何在保持原始排序的同时获取数组中N个最高数字?
我有,并希望得到b在提前
a = np.array([12.3,15.4,1,13.3,16.5])
b = ([15.4,13.3,16.5])
感谢。
答
好,我拿到这个:
- 使原始数组的副本;
- 对复制的数组进行排序以查找n个最高数字;
- 检查原始数组,并将其数字与前一步骤中的n个最高数字进行比较,然后在结果数组中移动所需数字。
var a = [12.3,15.4,1,13.3,16.5], n = 3, x = 0, c =[]; // c - the resulting array
var b = a.slice(); // copy the original array to sort it
for(var i = 1; i < b.length; i++) { // insertion sorting of the copy
var temp = b[i];
for(var j = i - 1; j >= 0 && temp > b[j]; j--) b[j + 1] = b[j];
b[j + 1] = temp;
}
for(var i = 0; i < a.length; i++) { // creating the resulting array
for(var j = 0; j < n; j++) {
if(a[i] === b[j]) {
c[x] = a[i]; x++; // or just c.push(a[i]);
}
}
}
console.log(c);
的例子Javascript编写的,是有点简单,但是,事实上,这是很语言无关,并没有工作。