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.

1
  • 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. Commented Jan 25, 2021 at 22:41

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

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!
Thanks! I implemented my idea and it works fine with the approach you recommended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.