1

I have 4 sorting algorithms which I want to visualize. I want to make them run at the same time. Should I write functions like bubbleSortStep instead of just bubbleSort to call it every second for example and execute one step. For example like this:

setInterval(() => {
  bubbleSortStep()
  insertionSortStep()
  quicksortStep()
}, 1000)

Or is it going to work fine if I create the sorting functions the normal way and add an interval to each of them like:

bubbleSort() {
  setInterval(() => {
    // sorting...
  }, 1000)
}

...same for other three, and call them afterwards.

bubblesort()
insertionSort()
quicksort()

The idea is coming from YouTube videos like this where the colors change all at once.

Andris Jefimovs
  • 689
  • 6
  • 17
  • 1
    Yes, use a single interval only. Btw, if you don't want to write functions that only do one step at a time, use generator functions where you can `yield` from the middle of control structures. – Bergi Jan 25 '21 at 22:41

1 Answers1

2

JS timer functions are not all that precise. If each different algorithm initializes a different timer, it might be an issue; they might get out of sync. (If you were using recursive setTimeouts, I know they'd definitely eventually get out of sync if the process took a long time.) Setting just a single timer and running one step for each algorithm inside that timer is probably a more trustworthy approach.

Note that the syntax you'll need will be something like

setInterval(() => {
  bubbleSortStep()
  insertionSortStep()
  quicksortStep()
}, 1000)

(setInterval accepts a function, not an object)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Yeah, it was more like pseudocode, but I will change that to be right. Thank you! That was my thought too, about getting out of sync. I will try your recommenced approach. Thank you for the answer! – Andris Jefimovs Jan 25 '21 at 19:36
  • Thanks! I implemented my idea and it works fine with the approach you recommended. – Andris Jefimovs Jan 27 '21 at 13:49