Is there a way to Bubble sort user input in Javascript?

I would like to allow the user to input numbers or generate random numbers. Then I would like to allow him to Bubble sort the numbers that are displayed (either the randomly generated ones or the numbers the user inputted). Any suggestions on how to bubble sort that specific array, even though it isn’t defined beforehand? Here is the code I have so far:

Thanks for the help

main.js

function randomNumbers() {
var num = document.getElementById("demo").innerHTML = Array.from({length: 30}, ()=>   Math.floor(Math.random() * 100));

}


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


function createList() {
    
    var number = prompt("Enter a maximum of 20 numbers, seperated by a comma");
    document.getElementById("outputnumber").innerText = number;
    
    }
 
function createSortedArray() {
var list = createList();
bubbleSort(list);
document.getElementById("sort").innerText = list;
  
  }
  
index.html

<body>

  <h1>Javascript Assignment</h1>
  <hr>
  <h3>Computer Platforms and Operating Systems - CIS 1102</h3>


  <p>Choose one of the following to create a list of numbers:</p

  <br>
  <p>
    <h4>i) Input Your Own Numbers</h4>
  </p>
 

 
  <p>
    <button onclick="createList(); " id="display" >Input Numbers</button>
  </p>

  <h4>ii) Random Generator</h4>
 
 
  <p>
  
    <input type = "button" onclick = "randomNumbers();" value = "Generate 30      Numbers" />
    
  </p>
  
  <br>
  <br>
  <br>
  
  <p id ="outputnumber"></p>
  <p id="demo"></p>


  <br>
  <hr>
  <br>
  <br>

  <p>Choose one of the following to sort the numbers:</p>

  <p>
      <button onclick="createSortedArray()" id = "bubble">Bubble sort</button>
  </p>


  <p>or</p>

  <p>
      <button onclick="" id = "bubble">Selection sort</button>
  </p>

  <p id="sort"></p>

  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>

  <hr>



</body>

109 thoughts on “Is there a way to Bubble sort user input in Javascript?”

Leave a Comment