I am trying to make a visual tool depicting how some sorting algorithms work similar to the video at this link except with 20 values only. The idea is to have bars that are are x percent long where x is a random number and I'm using grid to arrange the bars according to the numbers they represent. As a first I'm trying to do a brute force sort with the following code:
sleep(ms){
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function bruteForce() {
let vals = [...grid.querySelectorAll(".grid-item")];
for (let i = 0; i < vals.length; ++i) {
for (let j = 0; j < vals.length; ++j) {
if (i != j) {
vals[i].classList.add("compare");
vals[j].classList.add("compare");
const node1val = parseInt(vals[i].getAttribute("data-value"));
const node2val = parseInt(vals[j].getAttribute("data-value"));
if (node2val > node1val) {
console.log(node2val + " > " + node1val);
const node1Class = vals[i].className;
vals[i].className = vals[j].className;
vals[j].className = node1Class;
} else {
console.log(node2val + " < " + node1val);
}
await sleep(300);
vals[i].classList.remove("compare");
vals[j].classList.remove("compare");
}
}
}
}
The problem is that the values do not get sorted properly. The values 5, 87, 56, 45, 20 get sorted as 20, 45, 56, 87, 5.
The following is the console output:
87 > 5
56 > 5
*45 < 5*
*20 < 5*
5 < 87
56 < 87
45 < 87
20 < 87
5 < 56
87 > 56
45 < 56
20 < 56
*5 > 45*
87 > 45
56 > 45
20 < 45
*5 > 20*
87 > 20
56 > 20
45 > 20
I've highlighted the wrong ones. Why does the interpreter think 5 is greater than 20? How do I correct this?
Update: Fixed the string comparison. Still getting the wrong order of values. The console output, however is correct now. JSfiddle demo