这里是我的第二个解决方案:
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