I've got the following example.
<div class="parent">
<div data-id="5"></div>
<div data-id="2"></div>
<div data-id="3"></div>
<div data-id="1"></div>
<div data-id="4"></div>
</div>
If I want to order these div's in an ascending order (1,2,3,4,5). I would normally do a loop and append the div's in order to the parent
div. This will however mean I always make 5 changes to the dom (regardless of the order of the div's), one for each div.
You can however use the .insertBefore() method to order the div's correctly with only 2 changes!
5,2,3,1,4
Insert 1 before 2
5,1,2,3,4
Insert 5 behind 4 (using .insertBefore() and .nextSibling)
1,2,3,4,5
Question 1 By making only 2 changes to the DOM I assume less reflow ocours, making the '2 change' sorting action faster than the '5 change'sorting action. Is this correct?
Question 2 What sort of method/algorithm would be able to figure out to only do the insert 1 before 2
and 5 behind 4
?
Question 3 (bonus) Will this 'optimized' algorithm still be faster as the amount of items incease? Range 10 - 100 - 1.000 - 10.000 - 100.000
Maybe to clarify: I am not searching for a way to figure out the order (1,2,3,4,5) in the most optimal way. At a certain point I know the order but I want to compare the order agains the order of the div's and THEN figure out the least amount of operations.