Results Website Design's company banner with logo showing increased sales.
Results Website Design's company banner with logo showing increased sales.

Bubble Sort Algorithm

Bubble Sort is a basic sorting algorithm that makes several passes through a set of items. During each pass, pairs of items are compared, and the greater value "bubbles up" to the top (or in the case of the animation below, to the right). After one pass, the item to the farthest right is fully sorted. Each iteration further sorts the set, such that the number of iterations required to sort it fully is one less than the number of items.

Bubble Sort animation courtesy of visualgo.net

Sample Usage

The example below simulates an online store in which each fruit on display has attached to it an html data-* attribute in the format data-size="number."  This number is accessed by JavaScript to sort the fruit sizes from smallest to largest using the Bubble Sort algorithm. When sorting from largest to smallest, the algorithm is run in reverse. To sort alphabetically, the “data-fruit-name” attribute is used in conjunction with JavaScript’s built-in .sort() function. The buttons at the top allow you to see the sort methods in action.

Fresh Fruit Selection

Our Finest Peaches

Our peaches are grown locally at the Peach Tree Farm in Booneville, MO.  Only varieties currently ripening are shipped by refrigerated truck to arrive fresh.

Our Finest Blueberries

Our Blueberries radiate a deep, delicious blue hue that shows they are tasty and fresh. They are genetically selected to maintain their shape and firmness.  No more mushy supermarket blueberries!

Our Finest Strawberries

Our juicy and fresh strawberries are fit for a king's table.  These heart-shaped beauties are loaded with a day's supply of vitamin C and packed with fiber.

Our Finest Elderberries

Our signature elderberries are picked fresh and shipped straight to your doorstep under refrigeration.  They are rich in flavor, and maintain their gentle tanginess that makes them so delicious.

Our Finest Apricots

Our plump apricots are a customer favorite.  They taste sweet and are buoyant to the touch, without the mushiness you find in supermarket fruits.

Our Finest Cherries

Deep red and delicious.  Rich in antioxidants and fiber, these cherries are a best-seller.

HTML
<div class="panel-body">

  <div id="item-1" class="fruit-block peaches">
    <img src="https://resultswebsitedesign.com/path/red-peaches175x153.jpg">
    <div class="product-info-block">
      <h3>Our Finest Peaches</h3>
      <p class="product-description" data-fruit-name="peaches" data-size="6">Our peaches are grown...</p>
    </div>
    <span class="plus-or-minus icon-plus-circled"></span>
  </div>

  <div id="item-2" class="fruit-block blueberries">
    <img src="https://resultswebsitedesign.com/wp-content/path/blueberries175x153.jpg">
    <div class="product-info-block">
      <h3>Our Finest Blueberries</h3>
      <p class="product-description" data-fruit-name="blueberries" data-size="2">Our Blueberries radiate...</p>
    </div>
    <span class="plus-or-minus icon-plus-circled"></span>
  </div>

  <div id="item-3" class="fruit-block strawberries">
    <img src="https://resultswebsitedesign.com/path/strawberries175x153.jpg">
    <div class="product-info-block">
      <h3>Our Finest Strawberries</h3>
      <p class="product-description" data-fruit-name="strawberries" data-size="4">Our juicy and fresh...</p>
    </div>
    <span class="plus-or-minus icon-plus-circled"></span>
  </div>

  <div id="item-4" class="fruit-block elderberries">
    <img src="https://resultswebsitedesign.com/path/elderberries175x153.jpg">
    <div class="product-info-block">
      <h3>Our Finest Elderberries</h3>
      <p class="product-description" data-fruit-name="elderberries" data-size="1">Our signature elderberries...</p>
    </div>
    <span class="plus-or-minus icon-plus-circled"></span>
  </div>

  <div id="item-5" class="fruit-block apricots">
    <img src="https://resultswebsitedesign.com/path/apricots175x153.jpg">
    <div class="product-info-block">
      <h3>Our Finest Apricots</h3>
      <p class="product-description" data-fruit-name="apricots" data-size="5">Our plump apricots...</p>
    </div>
    <span class="plus-or-minus icon-plus-circled"></span>
  </div>

  <div id="item-6" class="fruit-block cherries">
    <img src="https://resultswebsitedesign.com/path/cherries175x153.jpg">
    <div class="product-info-block">
      <h3>Our Finest Cherries</h3>
      <p class="product-description" data-fruit-name="cherries" data-size="3">Deep red and delicious...</p>
    </div>
    <span class="plus-or-minus icon-plus-circled"></span>
  </div>

</div>
JavaScript
//ititialize click event for "largest-to-smallest"
$('.largest-to-smallest').click(function () {
  largestToSmallest = true;
  sortBySize();
});

//ititialize click event for "smallest to largest"
$('.smallest-to-largest').click(function () {
  smallestToLargest = true;
  sortBySize();
});

//ititialize click event for sorting alphabetically
$('.alphabetical').click(function () {
  alphabetize();
});

//initialize global variables to be used by sorting functions
var largestToSmallest = false;
var smallestToLargest = false;
var numberOfItems = document.getElementsByClassName('panel-body')[0].childElementCount;

//function to sort by size uses Bubble Sort algorithm
function sortBySize() {

  //Bubble Sort algorithm must run number of iterations equal to 1 less than number of items sorted to sort fully 
  for (i = 0; i < numberOfItems - 1; i++) {

    //compare each adjacent set of items, and move the larger item after the smaller item.  Number of comparisons required is one less than the number of items.
    for (j = 0; j < numberOfItems - 1; j++) {

      var $currentItem = $('.fruit-block:eq(' + j + ')');
      var $nextItem = $('.fruit-block:eq(' + (j + 1) + ')');

      //access the "data-size" attribute stored on the relevant fruit's HTML element
      var sizeOfCurrentItem = $currentItem.find('.product-description').get(0).getAttribute('data-size');
      var sizeOfNextItem = $nextItem.find('.product-description').get(0).getAttribute('data-size');

      //if "largest-to-smallest" was clicked, put larger of the two "fruit-block" compared first
      if (largestToSmallest) {

        if (sizeOfCurrentItem < sizeOfNextItem) {
          $($currentItem).insertAfter($nextItem);
        }
      }

      //if "smallest-to-largest" was clicked, put smaller of the two "fruit-block" compared first
      if (smallestToLargest) {

        if (sizeOfCurrentItem > sizeOfNextItem) {
          $($currentItem).insertAfter($nextItem);
        }
      }
    }
  }
  largestToSmallest = false;
  smallestToLargest = false;
}

//function to sort alphabetically
function alphabetize() {

  var alphabeticalArray = [];

  //cycle through each "fruit-block" 
  for (i = 0; i < numberOfItems; i++) {

    var $currentItem = $('.fruit-block:eq(' + i + ')');

    var $elementWithFruitName = $($currentItem).find('.product-description');
    var elementWithFruitName = $elementWithFruitName.get(0);

    //grab the "data-fruit-name" attribute for the current fruit being looped through
    var nameInDataAttribute = elementWithFruitName.getAttribute('data-fruit-name');

    //push fruit name coupled with the id of the larger "fruit-block" as an array of two items into the larger alphabeticalArray 
    alphabeticalArray.push([nameInDataAttribute, $($elementWithFruitName).parents('.fruit-block').attr('id')]);

  }

  //Now array is completed that contains pairs of [friut name, element id for that fruit block]
  //Sort this array alphabetically 
  alphabeticalArray.sort();

  //cycle through the alphabetized array
  for (i = 0; i < numberOfItems; i++) {

    //append the element id that is paired with each fruit as last on the page within the ".panel-body" container
    //the resulting order is aphabetical
    $(".panel-body").append($('#' + alphabeticalArray[i][1]));

  }
}