2017-02-27 87 views
1

我需要排序從最低到最高的用戶輸入的順序,並打印到我的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> 
+1

爲什麼'中的Array.sort()'不允許? – JohanP

+0

當前代碼在運行時實際上做了什麼?在顯示的代碼中,你永遠不會調用'bubbleSort()'。 – nnnnnn

回答

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

+1

謝謝你,我不敢相信我沒有注意到,哈哈。我累了。 –

+0

適合所有人,無後顧之憂。 :) – Paul

相關問題