數組排序並插入值算法(JavaScript)

問題:

先給數組排序,而後找到指定的值在數組的位置,最後返回位置對應的索引。html

示例:

舉例:where([1,2,3,4], 1.5) 應該返回 1。由於1.5插入到數組[1,2,3,4]後變成[1,1.5,2,3,4],而1.5對應的索引值就是1。數組

同理,where([20,3,5], 19) 應該返回 2。由於數組會先排序爲 [3,5,20],19插入到數組[3,5,20]後變成[3,5,19,20],而19對應的索引值就是2。this

解答:

function where(arr, num) {
// Find my place in this sorted array.
    arr.push(num);
    var newArr = arr.sort(function(a,b){return a-b});
    return newArr.indexOf(num);
}


where([2, 20, 10], 19);

連接:

https://www.w3cschool.cn/code...code

相關文章
相關標籤/搜索