2017-05-05 28 views

回答

1

好,我拿到這個:

  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編寫的,是有點簡單,但是,事實上,這是很語言無關,並沒有工作。

相關問題