1

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.

Elric
  • 21
  • 3
  • Hi, Elric; I am not fully sure what your ultimate goal is here. If you are looking to pause a thread to wait for user input (i.e. display two numbers and have a user sort them), then we wouldn't need a sorting algorithm. On the other hand, if you just wanted arrays sorted, then using the native Javascript `.sort()` function will be sufficient for anything other than massive data sets. If you are building a ranking system (for example) for top 10 things, then just store and update the rank, then sort and return. – Aaron Morefield Jan 07 '21 at 23:26
  • It is a ranking system with arrays yes, one of the uses I would make of it is input movies I've watched to help me get a clear ranking between which I like more than the others. I'm not sure what you mean by "storing and updating the rank" though, wouldn't it lead to the same problem elsewhere ? – Elric Jan 07 '21 at 23:40

1 Answers1

0

May not be ideal but a confirm box may be a quick solution since it will block the execution till user clicks a button:

if (confirm("Is " + left[0] + " less than " + right[0] + "?")) {
  res.push(left.shift());
} 
else {
  res.push(right.shift());
}

Comments in this answer says confirm box buttons cannot be changed to Yes/No.

If looking for alternatives, check the answers to this question.

burkay
  • 1,075
  • 1
  • 10
  • 20