简体   繁体   中英

Bubble sort in javascript

I've tried to use bubble sort in javascript, but stuck up while swapping the numbers. The idea is to group the numbers(eg: input: 154514, output should be : 114455). So I tried to use bubble sort to get the above output.

My code is here:

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));

The swapping is not working. Kindly help.

Thanks so much in advance.

So you're actually really close. The problem you're running into is that you can't change the value of a specific character in a string by accessing the character at an index because strings are immutable. So if I have the string var a = "test"; and I do a[2] = 'p'; a will still be "test" and not "tept" because strings are immutable. That being said what we need to do to fix your sort is to convert the string to an array (which is mutable) and then back to a string like this:

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));

So to turn the string into an array we're using split() and then join() to convert an array back into a string.

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

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

Arrays can be sorted with with sort method - so let's just use that:

 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 converts the argument to a string, splits it into an array, sorts it numerically and then joins it up again. If you wanted a number to be returned (instead of a string) just use parseInt .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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