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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…