繁体   English   中英

气泡在javascript中排序

[英]Bubble sort in javascript

我尝试在JavaScript中使用冒泡排序,但在交换数字时卡住了。 想法是将数字分组(例如:输入:154514,输出应为:114455)。 因此,我尝试使用冒泡排序来获取上述输出。

我的代码在这里:

function numSort(num){
var temp = '';
var temp1 = '';
arr = num.toString();
var n = arr.length; 
for(i=0; i<n-1; i++){
    for(d=0; d<n-i-1; d++){
        if(arr[d] > arr[d+1]){
            temp = arr[d];//here I'm trying to swap the inputs as: 89, but it's not letting.
            arr[d] = arr[d+1];
            arr[d+1] = temp;                
        }console.log(arr[d]);
}       
}   
}console.log(numSort(98));

交换不起作用。 请帮助。

非常感谢。

所以您实际上真的很亲近。 您遇到的问题是,由于字符串是不可变的,因此无法通过访问索引处的字符来更改字符串中特定字符的值。 因此,如果我有字符串var a = "test"; 并且我做a[2] = 'p'; 因为字符串是不可变的,所以a仍将是"test"而不是"tept" 话虽这么说,我们需要解决的问题是将字符串转换为数组(可变的),然后再转换为这样的字符串:

function numSort(num){
    var temp = '';
    var temp1 = '';
    arr = num.toString().split(''); // turn the string into an array
    var n = arr.length; 
    for(i=0; i<n-1; i++){
        for(d=0; d<n-i-1; d++){
            if(arr[d] > arr[d+1]){
                temp = arr[d]; // here I'm trying to swap the inputs as: 89, but it's not letting.
                arr[d] = arr[d+1];
                arr[d+1] = temp;                
            }
            console.log(arr[d]);
          }       
    }
    return arr.join(''); // you can optionally do a parseInt() here to convert it back to a number
}
console.log(numSort(98));

因此,要将字符串转换为数组,我们使用split() ,然后使用join()将数组转换回字符串。

为什么不将字符串转换为数组?

arr = num.toString().split("");

可以使用sort方法数组进行排序-因此,我们就可以使用它:

 function numSort(num) { return num.toString().split('').sort().join(''); } console.log( numSort(154514) ); // 114455 console.log( numSort(765432) ); // 234567 console.log( numSort(32) ); // 23 

numSort将参数转换为字符串,将其拆分为数组,对其进行数字排序,然后再次将其连接起来。 如果您希望返回一个数字(而不是字符串),请使用parseInt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM