Friday, 16 November 2012

Simple jQuery & JavaScript Bubble Sort

jQuery is pretty powerful, and you should leverage it as much as possible. Someone might say but what if the client has javascript disabled? My response is simple, they don't even deserve to sort. anyway here's a quick example.

Here's the HTML

<html>
  <head>
    <title>Date Example</title>
    <script src = "jquery-1.6.1.js"></script>
    <script src = "script.js"></script>
  </head>
  <body>
    <input type = "button" value = "sort" onclick="sort();" />
    <div>Nov 12, 2012 1:00 PM EST</div>
    <div>Oct 09, 2012 5:00 PM EDT</div>
    <div>Nov 29, 2012 2:00 PM EST</div>
    <div>Oct 09, 2012 5:00 PM EDT</div>
    <div>Nov 09, 2012 2:00 PM EST</div>
    <div>Nov 19, 2012 2:00 PM EST</div>
    <div>Nov 09, 2012 2:00 PM EST</div>
    <div>Nov 29, 2012 2:00 PM EST</div>
    <div>Nov 05, 2012 12:00 AM EST</div>
    <div>Nov 08, 2012 9:10 AM EST</div>
  </body>
</html>

and followed by the JQuery

function sort()
{
  var swap = false
  var prev = null;
 
  do {
    prev = null;
    swap = false;
    $('div').each(
    function (indexelement)
    {
      if(prev != null && shouldSwap(prev,element))
      {
        $(this).after($(prev));
        swap = true;
      } 
  
      prev = element;
    });
  }while(swap)
}

function shouldSwap(d1d2)
{
  var dateOne = new Date($(d1).text());
  var dateTwo = new Date($(d2).text());
 
  return dateOne > dateTwo;
}

or if you prefer vanilla JavaScript (which I now do, since I haven't written JQuery in years)

function sort() {
  let swap = false
  let prev = null;
  let predicate = (d1d2=> new Date(d1) > new Date(d2);
  
  do { 
    prev = null;
    swap = false;
    const divs = [...document.getElementsByTagName("div")];
    
    divs.forEach((elementindex=> {
        if(prev != null && predicate(prev.innerText, element.innerText)) {
          element.after(prev);
          swap = true;
        } 
        prev = element;
   });
 } while(swap)
}

now you may notice this is not the most efficient bubble sort, it's a simple example to prove a point not efficiently sort 1'000'000 records.