gpt4 book ai didi

javascript - 选择排序后查找排序数组中数字位置的代码不稳定?

转载 作者:行者123 更新时间:2023-11-30 15:36:36 25 4
gpt4 key购买 nike

此代码在插入另一个元素后对数组进行排序,并返回插入元素在已排序数组中的索引(需要返回第一个位置或可能的最低索引)。

代码:

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

什么坏了?

最佳答案

您使用 Array#sort()没有 compareFunction,这意味着您得到的结果是每个元素都被视为字符串而不是数字。这可能会导致错误的索引。

var sortedarr = sort(combinelists(arr,num).sort());
// ^^^^^^

你可以使用像这样的回调

var sortedarr = sort(combinelists(arr,num).sort(function (a, b) { return a - b; }));

用于按数字排序。

关于javascript - 选择排序后查找排序数组中数字位置的代码不稳定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41445051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com