簡體   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