T
T
Torna2016-05-26 16:07:14
JavaScript
Torna, 2016-05-26 16:07:14

What algorithm to use to speed up sorting divs?

Tell me, who knows what is the best algorithm for sorting. about 2 thousand divs.
And it is desirable to give an example not with an array, but with a div.
The fact is that the standard comparison algorithm leads to a page freeze for 8 seconds.

var result_sort = false;
$('.hotel-list').on('click','#sort-price',function()
{
   var sorted = $('.hotel-list-item').sort(function(a,b)
   {
  return (result_sort == (convertToNumber($(a).find('#price').html()) < convertToNumber($(b).find('#price').html()))) ? 1 : -1;
   });						
       result_sort = result_sort ? false : true;
      $('.hotel-list-cn').html(sorted);
});

var convertToNumber = function(value)
{
     return parseFloat(value);
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Aves, 2016-05-26
@Torn

Native sorting is the best option. The problem is not in it, and not in 2000 divs, but in the fact that the comparison function is executed about 20,000 times, and it works with dom

convertToNumber($(a).find('#price').html()) < convertToNumber($(b).find('#price').html()))

This convertToNumber needs to be done once when creating an array, this will immediately reduce the sorting time by an order of magnitude.
jsbin example

A
Alexander Aksentiev, 2016-05-26
@Sanasol

Yes, the page from 2000 divs will be bent even without sorting.
You need to make a normal page, and not look for an algorithm.
And sort the data (array), and not parse the entire page, and even with a huge amount of find.
8 seconds is probably still a good computer for you, but something older will not sag at all.

S
Sergey Savostin, 2016-05-26
@savostin

read here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question