【发布时间】:2021-01-31 11:15:07
【问题描述】:
我想允许用户输入数字或生成随机数。然后我想让他对显示的数字进行冒泡排序(随机生成的数字或用户输入的数字)。关于如何对特定数组进行冒泡排序的任何建议,即使它没有事先定义?这是我到目前为止的代码:
感谢您的帮助
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>
【问题讨论】:
-
PS 格式化您的代码。此外,
</hr>是无效标签 -
这个问题对我来说还不清楚。您发布了一个带有冒泡排序功能的代码,并且您正在询问如何对数组进行排序。你的问题到底是什么?
-
您的代码中有一个显然没问题的冒泡排序实现,可用于对任何数字数组进行排序。您没有的是一组数字,因为您在文本框中有文本。使用
string.split()和parseInt()(在循环中或array.map())从输入或您自己生成的字符串中获取数字数组。
标签: javascript arrays user-input bubble-sort