Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

javascript - Synchronize function execution (sorting algorithms)

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.

question from:https://stackoverflow.com/questions/65891214/synchronize-function-execution-sorting-algorithms

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...