skip to Main Content

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:

  1. 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.
  2. 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


  1. 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.

    Login or Signup to reply.
  2. 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.

    DocumentFragment

    The DocumentFragment interface represents a minimal document object
    that has no parent.

    It is used as a lightweight version of Document that stores a segment
    of a document structure comprised of nodes just like a standard
    document. The key difference is due to the fact that the document
    fragment isn’t part of the active document tree structure. Changes
    made to the fragment don’t affect the document.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search