I have a list of dozens DIVs like
<div data-sort="7.5"></div>
<div data-sort="3.2"></div>
<div data-sort="2.15"></div>
<div data-sort="-1.78"></div>
<div data-sort="-2.39"></div>
and so on and I get new DIVs with an ajax request. I need to insert the new DIV so the order with "data-sort" remains intact in descending order.
Maybe not elegant, but fast enough...
In your
success
handler:jsFiddle
It's not as optimal as can be, but I would just sort the divs each time the ajax request completes:
If that takes too long, you'll just have to cycle through the divs (via
.each
?) and find the first one whosedata-sort
is smaller.You can use your custom logic also. Please try it.
Here is your HTML
javascript code
The fastest algorithm to do this insertion (
O(logN)
) would be to do a binary search for the values that the new item goes between. Assume that the list is already sorted first (if that's not done automatically, use one of the other answers here):http://jsfiddle.net/ExplosionPIlls/SdjAy/1/
I've solved it like this with help from the answers here:
which seems to work ok and fast enough... anyone sees any flaws in it?