Reputation: 31
My HTML and JS are all here:
https://gist.github.com/RoloRobot/b2e15af9ab0d8c1bdbdd
My quicksort works perfectly well but when I try to test it, I can only view it in console. It generates random numbers everytime. I am trying to make it so that when I press the "Commence Quicksort" button, the sorted random sequence will appear below the button and will continue for however many times I press the button.
Any help would be appreciated!
Upvotes: 0
Views: 161
Reputation: 7059
Stack snippets are your friend!
Your code seems to work great when I replace console.log
with 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>
Upvotes: 1
Reputation: 1061
I think you are looking for 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>');
});
}
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
Upvotes: 1
Reputation: 107
Add the following code after your console.log();
var quickTimes = document.getElementById("QuickTimes");
var child = document.createTextNode(array);
quickTimes.appendChild(child);
var linebreak = document.createElement('br');
quickTimes.appendChild(linebreak);
Upvotes: 0