jcjohnson / sorting.js

Visualize sorting algorithms in Javascript
MIT License
59 stars 10 forks source link

A Stop Button #1

Open Travis-S opened 9 years ago

Travis-S commented 9 years ago

I noticed there's a start button, but not one for stopping. This might be nice for those users who accidentally make the initial array size too large. (Not naming names, but one user set the array size to 1500 and then watched as their computer froze up!)

jcjohnson commented 9 years ago

Not a bad idea. Unfortunately it would take some major refactoring to make this work. Since Javascript is single-threaded, I considered two basic designs for getting the animation to work:

(1) Sorting the array builds up a data structure describing the steps taken; once sorting is done, this data structure is used to replay the sorting process for the animation. This allows the code for the sorting algorithms to look like their textbook descriptions, but causes everything (browser events, animation, etc) to block until the array is sorted.

(2) Use some sort of callback mechanism, where each sorting algorithm passes part of itself as a callback to the AnimatedArray. This is probably the more technically correct way to achieve this sort of animation in Javascript, since it allows animation and other browser events to take place while the sorting algorithm is running. However this would probably make the sorting code much uglier and harder to understand.

I opted for (1), and a stop button is only possible with (2).

However maybe a more pragmatic solution is just to set a maximum array size of 500 or so for the quadratic sorting algorithms.

Travis-S commented 9 years ago

Since Javascript is single-threaded, ...

I have no idea what this means, but since it sounds technical, I will believe it.

However maybe a more pragmatic solution is just to set a maximum array size of 500 or so for the quadratic sorting algorithms.

That's definitely a good approach. I think the user in question would have appreciated that solution, especially if it came with a little warning box: What are you doing?! Don't you have better things to do, like science?