I'm trying to write a script that uses the bubble sort method to take an array and order it by values.
It works fine with single digits, but fails to work once I enter any inputs that are non-single digit.
<!DOCTYPE html>
<html>
<body>
<p> Click the button to enter and display an array of numbers! </p>
<button onclick="sortFunction()">Click Me</button>
<script>
function sortFunction()
{
var totalNums = prompt("How many numbers would you like to enter?","");
var numsArray = [];
for(i=0; i<totalNums; ++i)
{
if(nums != "x")
{
var nums = prompt("Please enter number " ,"");
numsArray[i] = nums;
document.getElementById("unsorted").innerHTML = "Orignal Numbers: " + numsArray;
}
}
var length = numsArray.length;
var swapped;
do
{
swapped = false;
for (var j=0; j < length-1; j++)
{
if (numsArray[j] > numsArray[j+1])
{
var temp = numsArray[j];
numsArray[j] = numsArray[j+1];
numsArray[j+1] = temp;
swapped = true;
}
}
document.getElementById("sorted").innerHTML = numsArray;
} while (swapped);
}
</script>
<div id ="unsorted">Unsorted</div>
<div id ="sorted">Sorted</div>
</body>
</html>
PS - Just out of curiosity... How would I make it display the array each iteration of the outer loop when sorting? So it displays the code run by run.
Thanks!