javascript中的冒泡排序

Bubble sort in javascript

本文关键字:冒泡排序 javascript      更新时间:2023-09-26

我曾尝试在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。