如何在保持原始排序的同时获得数组中的 N 个最高数字?

How to get the N highest numbers on an array while keeping original sorting?

例如,对于 N 个最高数字,假设 N = 3

我有a,想得到b

 a = np.array([12.3,15.4,1,13.3,16.5])
 b = ([15.4,13.3,16.5])

提前致谢。

好吧,我对此的看法:

  1. 复制原始数组;
  2. 对复制的数组进行排序,找出n个最大的数;
  3. 遍历原始数组,将其数字与上一步中的 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 编写的,有点直截了当,但实际上,它与语言无关并且可以完成工作。