从最低到最高对用户输入进行排序

时间:2017-02-27 04:08:38

标签: javascript

我需要将用户输入的顺序从最低到最高排序并打印到我的p id。

实现排序算法以对n个整数进行排序(不使用数组的sort()方法)。

在输出中打印排序数组。

<!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>

1 个答案:

答案 0 :(得分:1)

看起来你的代码是有效的,除了你必须实际调用bublesort函数然后该函数需要返回结果。

<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);
      }
   }
}

numbers = bubbleSort(numbers);

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;
            }
        }
    }
    return numbers;
}
function searchInput() {

}
}
</script>

</body>

这里是fiddle that works