我的HTML和JS都在这里:
https://gist.github.com/RoloRobot/b2e15af9ab0d8c1bdbdd
我的快速排序功能非常好但是当我尝试测试它时,我只能在控制台中查看它。它每次都会产生随机数。我正努力做到这一点,当我按下" Commence Quicksort"按钮,排序的随机序列将出现在按钮下方,并且会按下按钮多次继续。
任何帮助将不胜感激!
答案 0 :(得分:1)
我认为您正在寻找insertAdjacentHTML
<!-- YOUR HTML -->
<button onclick="var a = []; RandNum(a, 9); sort(a);">
Quicksort Commence!</button>
<div id="QuickTimes">
</div>
========================================================
//The javascript you need
function sort(array){
//find the element you want to insert html into
var el = document.getElementById('QuickTimes');
quickSort(array,0,array.length - 1);
//for each item in your array insert a p element with the item in the array as the text
array.forEach(function (item) {
el.insertAdjacentHTML('beforeend', '<p>' + item + '</p>');
});
}
参考:https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
答案 1 :(得分:1)
Stack snippets是你的朋友!
当我用console.log
document.getElementById("QuickTimes").insertAdjacentHTML("beforeend",array);
时,您的代码似乎很有效
function quickSort(array, left, right){
var len = array.length,
pivot,
partitionIndex;
if(left < right){
pivot = right;
partitionIndex = partition(array, pivot, left, right);
quickSort(array, left, partitionIndex - 1);
quickSort(array, partitionIndex + 1, right);
}
return array;
}
function partition(array, pivot, left, right){
var pivotValue = array[pivot],
partitionIndex = left;
for(var i = left; i < right; i++){
if(array[i] < pivotValue){
swap(array, i, partitionIndex);
partitionIndex++;
}
}
swap(array, right, partitionIndex);
return partitionIndex;
}
function swap(array, i, j){
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
function RandNum(array, quantity) {
var num;
for (var i = 0; i < quantity; i++) {
num = Math.floor(Math.random() * (100 - 50 + 1)) + 10;
if (num !== array[i - 1]) {
array.push(num);
} else {
i--;
}
}
}
function sort(array){
quickSort(array,0,array.length - 1);
document.getElementById("QuickTimes").insertAdjacentHTML("beforeend",array+"<br/>");
}
<button onclick="var a = []; RandNum(a, 9); sort(a);">Quicksort Commence!</button>
<div id="QuickTimes"> </div>
答案 2 :(得分:0)
在console.log();
之后添加以下代码var quickTimes = document.getElementById("QuickTimes");
var child = document.createTextNode(array);
quickTimes.appendChild(child);
var linebreak = document.createElement('br');
quickTimes.appendChild(linebreak);