1
此代碼在插入另一個元素後對數組進行排序,並返回已排序數組中插入元素的索引(需要返回第一個位置或最低可能的索引)。選擇排序不穩定後在代碼排序陣列中查找編號的位置的代碼?
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
什麼是壞了?
你真的有問題嗎? –
有一個[代碼評論堆棧交換站點](https://codereview.stackexchange.com/) –
耶穌夥計,是的,我有一個問題 - 爲什麼它爲一些而不是其他人?順便說一句,「如果它沒有通過所有的測試,它沒有準備好審查代碼審查」。所以,是啊.. –