// Change ITEMS for amount of bars.
const ITEMS = 50;
// Delay between comparasins.
let sortDelay = 100;
// Delay between sorting simulations.
let restartDelay = 1000;
// Grab canvas and context.
let canvas = document.getElementById('display');
let context = canvas.getContext('2d');
// Declare array to be ITEMS long.
let list = new Array(ITEMS);
let comparison_count = 0;
let swap_count = 0;
// Flags used to determine if bg or bars need redrawn.
let updateBG = true;
let updateBars = true;
// loopBlock is briefly enabled when sorting has finished to give a view of the finished sort.
let loopBlock = false;
// Setup event listeners for window.
function setupCanvas() {
// Setup event listeners for load and window resize.
window.addEventListener('load', canvasResize);
window.addEventListener('resize', canvasResize);
}
// Initializes the list of 100 random numbers.
function initList() {
for (let i = 0; i < ITEMS; i++)
list[i] = Math.round(Math.random() * 100);
comparison_count = 0;
swap_count = 0;
}
// This function grabs the width and height of the window
// and resizes the canvas in the event of loading or resizing.
function canvasResize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// removed the following two lines to make printing t text work properly (not inverted)
//context.translate(0, canvas.height);
// context.scale(1, -1);
updateBG = true;
updateBars = true;
}
// Finds the largest number in the list.
function max() {
let maximum = list[0];
for (let i = 1; i < ITEMS; i++)
maximum = list[i] > maximum ? list[i] : maximum;
return maximum;
}
// Comparing indicators to draw in different colors.
// cmp1 and cmp2 are two indices being compared, make them
// negative to mean a switch is happening
let cmp1 = 0;
let cmp2 = 0;
// Plot each index of list[].
function plotBars() {
let length = list.length;
let barWidth = canvas.width / length;
let barScale = canvas.height / max();
for (let i = 0; i < ITEMS; i++) {
let x = i * barWidth;
let h = list[i] * barScale;
let y = canvas.height - h;
context.save();
if (i == cmp1 || i == cmp2)
context.fillStyle = 'white';
else if (i == -cmp1 || i == -cmp2)
context.fillStyle = 'yellow';
else
context.fillStyle = '#e78fb3';
context.fillRect(x+1, y, barWidth-2, h);
context.fillStyle = 'white';
context.font = "12px Ariel";
context.fillText(list[i], x+4, y+12);
context.restore();
}
}
// Draws the black background.
function drawBackground() {
// Save context to stack.
context.save();
context.fillStyle = 'black';
context.fillRect(0, 0, canvas.width, canvas.height);
// Pops most recently saved canvas state off stack.
context.restore();
context.fillStyle = '#e78fb3';
context.font = "30px Ariel";
context.fillText("Selection Sort, " + ITEMS + " items", 10, 35);
context.fillStyle = 'white';
context.fillText('Comparing - white', 10, 60);
context.fillStyle = 'yellow';
context.fillText('Swapping - yellow', 10, 85);
context.fillStyle = 'grey';
context.fillText('# comparisons so far: ' + comparison_count, 10, 110);
context.fillText('# swaps so far: ' + swap_count, 10, 135);
}
// These are some variables that flag and alter various parts
// of the sort. You may need to add/remove/modify your own
// depending on the complexity of your sorting method.
let sortStarted = false;
let sortFinished = false;
let sortIndex = 0;
// adapted from https://en.wikipedia.org/wik
// Sorting function. This example uses bubble sort.
function sortStart() {
// Finished is used to mark when no swaps were done in a sort loop.
// Think of it as finishing one sorting loop.
let finished = false; // note - set to false except for when gap is 1
// tmp is used as a temporary value when swapping.
let tmp;
// Flip the sortStarted flag.
sortStarted = true;
// setInterval() runs once every <sortDelay>
let sortLoop = setInterval(function() {
document.body.onkeyup = function(e){
if(e.keyCode == 32) loopBlock = !loopBlock;
}
if (loopBlock) {
// Paused
context.fillStyle = 'red';
context.font = "30px Ariel";
context.fillText("PAUSED", 30, 155);
} else {
// Selection sort algorithm
let min = sortIndex;
for (let j = sortIndex + 1; j < ITEMS; j++) {
if (list[min] > list[j]) {
min = j;
}
}
// If this is true, we're swapping something:
if (min !== sortIndex) {
let tmp = list[sortIndex];
list[sortIndex] = list[min];
list[min] = tmp;
cmp1 = -min;
cmp2 = -sortIndex;
swap_count++;
// Else we're just comparing:
} else {
cmp1 = sortIndex;
cmp2 = sortIndex+1;
comparison_count++;
}
// Flag that background and bars need updated
updateBG = true;
updateBars = true;
sortIndex++;
// Reached end of list.
// If list has been scanned once with no swaps,
// sortFinish will be set and sort will end.
// Otherwise start over from 1.
if (sortIndex == ITEMS-1) {
if (finished) {
sortFinished = true;
clearInterval(sortLoop);
}
sortIndex = 0;
finished = true;
}
}
// Repeat once every <sortDelay>.
}, sortDelay);
}
// Setup initializes the canvas as well as the list of random nums.
function setup() {
setupCanvas();
initList();
}
function loop() {
if (!loopBlock) {
// If background needs updated, redraw background.
if (updateBG) {
updateBG = false;
drawBackground();
}
// If bars need updated, replot.
if (updateBars) {
updateBars = false;
plotBars();
}
// Starts the sort if it isn't looping already.
if (!sortStarted)
sortStart();
// Checks if sort has completed. Briefly blocks looping while re-initializing the list, sortStarted, and sortFinished variables.
if (sortFinished) {
loopBlock = true;
setTimeout(function() {
initList();
sortStarted = false;
sortFinished = false;
loopBlock = false;
// Fix gap after refresh
gap = ITEMS;
}, restartDelay);
}
}
}
// Main function which runs the setup and holds the main infinite loop.
(function main() {
// Setup the canvas and list.
setup();
(function mainLoop() {
loop();
// requestAnimationFrame calls mainLoop infinitely
requestAnimationFrame(mainLoop);
})();
})();