I’m making a project this week that consists of a page that displays real-time sorting of elements for the following sorting algorithms: Selection sort, Insertion sort, Bubble sort, Merge sort, and Quick sort. To achieve this, I’ll not only have to implement the algorithms but also make the DOM react accordingly. This has raised the question of what would be the best methods to accomplish this.
I’ve thought of two solutions:
- Every time an array of elements is sorted, reload those elements on the screen. However, this solution doesn’t seem optimal for performance since, despite using it in other projects, here the elements would be reloaded thousands of times within a few seconds.
- Declare the elements with "position: absolute" and update the "left" property for each one whenever an element changes position in the array. I’ve used this approach in my previous project, so it is currently my favorite.
My question is: does anyone have a better method to achieve this goal. If not, which of the two options should I use? Is the first solution really bad for performance, or can JavaScript handle it well?
2
Answers
The basic issue here is do you want to see the sorting changing the DOM visually? Because JavaScript is single-threaded, this is rather complicated. To see the changes visually, you’d need to save the sorting state in an object and use setInterval / setTimeout to start the sorting again after the UI has updated.
Coding-wise, the much easier, faster way if you don’t need visual confirmation is to count the number of position swaps with each sort and report the numbers at the end.
I think a document fragment fits here. Note that
appendChild()
moves (removes) that particular node to the target element. If you want to keep the selected node you must.clone
.