我需要排序從最低到最高的用戶輸入的順序,並打印到我的p id。從最低到最高排序用戶輸入
實現排序算法來排序n個整數(不使用array()方法)。
在輸出中打印排序數組。
<!DOCTYPE html>
<html>
<head>
<title>User Input, Sort and Find!</title>
<style>
</style>
</head>
<body>
<h2>Enter 4 numbers user!</h2>
<p id="myprint"></p>
<button onclick="userInput()">Input your Numbers!</button>
<button onclick="searchInput()">Find an inputed number in your array! </button>
<script>
var numbers = [];
function userInput() {
for(var i = 0; i < 4; i++){
var num = prompt("Enter a number 1 at a time, from 1-9 until prompts ask you 4 times:");
if (isNaN(num)) {
alert("Enter a number!");
--i; // reset the counter for amount of numbers entered
}
if(!isNaN(num)) {
if(num % 1 != 0){
alert("Enter a whole number!")
--i; // reset the counter for amount of numbers entered
}else{
numbers.push(num);
}
}
}
document.getElementById("myprint").innerHTML = "Your numbers are" + numbers;
//Sort the array and print numbers in inner html
function bubbleSort(numbers) {
var length = numbers.length;
for (var i = (length - 1); i >= 0; i--) {
for (var j = (length - i); j > 0; j--) {
if (numbers[j] < numbers[j - 1]) {
var nmbr = numbers[j];
numbers[j] = numbers[j - 1];
numbers[j - 1] = nmbr;
}
}
}
}
function searchInput() {
}
}
</script>
</body>
</html>
爲什麼'中的Array.sort()'不允許? – JohanP
當前代碼在運行時實際上做了什麼?在顯示的代碼中,你永遠不會調用'bubbleSort()'。 – nnnnnn