I coded a webpage in JS that lets the user put the number of elements he likes to then allow him to get a ranking of these elements, to sort them. I did it with all the comparisons at first so that I could plan ahead which comparisons I needed before asking the user but...
This is O(n²) and obviously not suitable for a number of elements greater than, say, 5.
I am now trying to implement merge sort, but I can't plan anymore all the comparisons needed and I have to ask for the user in the merge process. Here's what my code looks like :
async function mergeSort(array) {
if (array.length < 2) return array;
const middle = Math.floor(array.length / 2);
const left = array.slice(0, middle);
const right = array.slice(middle, array.length);
const sortedLeft = mergeSort(left);
const sortedRight = mergeSort(right);
return mergeArrays(sortedLeft, sortedRight);
}
function mergeArrays(left, right) {
const res = [];
while (left.length && right.length) {
document.getElementById("left").innerHTML = left[0];
document.getElementById("right").innerHTML = right[0];
//???
res.push( /*left greater than right?*/ ? right.shift() : left.shift());
}
while (left.length) {
res.push(left.shift());
}
while (right.length) {
res.push(right.shift());
}
return res;
}
Ideally, the code waits for the user to click either on the "left" or "right" HTML button and then goes on with the sorting process. But I don't see how to do that, even with promises or callbacks.