此代码在插入另一个元素后对数组进行排序,并返回已排序数组中插入元素的索引(需要返回第一个位置或最低可能索引)。
CODE:
function getIndexToIns(arr, num) {
// Find my place in this sorted array.
var sortedarr = sort(combinelists(arr, num).sort());
var pos = [];
for (i = 0; i < sortedarr.length; i++) {
if (sortedarr[i] == num) {
pos.push(i);
}
}
return pos[0];
}
function combinelists(arr1, arr2) {
var newarr = [];
newarr.push(arr2);
for (i = 0; i < arr1.length; i++) {
newarr.push(arr1[i]);
}
return newarr;
}
function sort(arr) {
if (arr.length < 2) {
return arr;
} else {
var l = arr.length / 2;
var leftarr = arr.slice(0, l);
var rightarr = arr.slice(l);
return combine(sort(leftarr), sort(rightarr));
}
}
function combine(array, another_array) {
var result = [];
while (array.length && another_array.length) {
if (array[0].age <= another_array[0].age) {
result.push(array.shift());
} else {
result.push(another_array.shift());
}
}
while (array.length)
result.push(array.shift());
while (another_array.length)
result.push(another_array.shift());
return result;
}
console.log(getIndexToIns([2, 20, 10], 19));
console.log(getIndexToIns([2, 5, 10], 15));
但它似乎并不适用于所有输入:
It works for the following tests:
[10, 20, 30, 40, 50], 30
[40, 60], 50
[2, 20, 10], 19
But it doesn't work for these:
[2, 5, 10], 15
[5, 3, 20, 3], 5
[3, 10, 5], 3
[10, 20, 30, 40, 50], 35
什么坏了?
答案 0 :(得分:2)
您使用Array#sort()
而不使用compareFunction
,这意味着您会得到一个结果,其中每个元素都被视为字符串而不是数字。这可能导致错误的索引。
var sortedarr = sort(combinelists(arr,num).sort());
// ^^^^^^
你可以使用像
这样的回调var sortedarr = sort(combinelists(arr,num).sort(function (a, b) { return a - b; }));
按数字排序。