這裏是我的第二個解決方案:
function mysort(array) {
var index, value, badValues,
len = array.length;
// find values at a bad place
badValues = [];
for (index = 0; index < len; index++) {
if (array[index] !== index + 1 - badValues.length) {
badValues.push(array[index]);
}
}
// move those to the end in increasing order
while (badValues.length > 0) {
// minimum bad value
value = Math.min.apply(null, badValues);
index = array.indexOf(value);
// move to the end
array.splice(index, 1);
array.push(value);
// one bad solved
badValues.splice(badValues.indexOf(value), 1);
}
return array;
}
這裏是一個demo fiddle。 如您所見,輸入[1,2,9,3,4,8,5,6,7]
按2次移動排序,並且完全隨機的或反轉的列表仍然是n-1
移動。
它與哪種語言無關。 OP只需要一個算法,可以用最少的步驟完成他想要的任務。 – Ranveer
你是最初排序的列表嗎?如果是的話,這是一個非常簡單的問題,可以用少於「n」的步驟完成。 – Ranveer
我可以用它的索引來表示列表中的每個元素,所以是的,說它最初是按遞增順序排序的。 – user433342