以下代码应将字符串转换为数字数组,并按降序对它们进行排序。 目的是找到 sort() 方法的替代方法。
出了点问题。如果 7 被放置在数组的前半部分(如示例中所示),则代码将无法正常工作。如果将 7 替换为比上一个更大的数字(示例中为 22),则代码将正常工作。
无论数字的位置如何,我都希望让它正常工作。
var row = '92 43 7 119 51 22';
var row = row.split(' ');
var column = row.map(Number);
function arrangeNum(column) {
for (var i = 0; i <= column.length - 1; i++) {
for (var j = column.length - i; j >= 0; j--) {
if (column[j] > column[j - 1]) {
var temp = column[j];
column[j] = column[j - 1];
column[j - 1] = temp;
}
}
}
return column;
}
console.log(arrangeNum(column));
最佳答案
Something is wrong. If 7 is placed in the first half of the array (like in the example), the code does not work properly.
这是因为你的第二个循环对j
的初始化
替换
for (var j = column.length - i; j >= 0; j--) {
与
for (var j = column.length - 1; j >= i; j--) {
请注意,j
已初始化为 column.length - 1
,但只允许低至 i
演示
function arrangeNum(column) {
for (var i = 0; i <= column.length - 1; i++) {
for (var j = column.length - 1; j >= i; j--) {
if (column[j] > column[j - 1]) {
[column[j], column[j - 1]] = [column[j - 1], column[j]];
}
}
}
return column;
}
console.log( arrangeNum( '92 43 7 119 51 22'.split( /\s+/ ).map( Number ) ) );
关于javascript - JavaScript 中的数字排序代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47908174/