Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

javascript - Bubble sort an array that is randomly generated each time

I'd like to bubble-sort the array that is randomly generated, each time the user presses the button. But I'm not sure how to bubble sort the array, when it is not yet defined. Can I link the array generated by the Random generator to my Bubble sort function?

Here is what I have tried:

var num = Array.from({length: 30}, ()=> Math.floor(Math.random() *  100));

function randomNumbers() {
document.getElementById("demo").innerHTML = num;
}

function bubbleSort(num) {
var swapped;
do {
    swapped = false;
    for (var i=0; i < num.length-1; i++) {
        if (num[i] > num[i+1])  {
            var temp = num[i];
            num[i] = num[i+1];
            num[i+1] = temp;
            swapped = true;
        }
    }
} while (swapped);  

bubbleSort(num);
document.write(num);

}
question from:https://stackoverflow.com/questions/65917388/bubble-sort-an-array-that-is-randomly-generated-each-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...