Bubble sort algorithm in JavaScript

November 16, 2014

Reading time ~2 minutes

What is Bubble sort algorithm ?

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements “bubble” to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, it is too slow for practical use, even compared to insertion sort.[1]

http://en.wikipedia.org/wiki/Bubble_sort

Code

/***************************************
 * sort
 ***************************************/
var bubbleSort = function(list){
  var k = 0,
      l = list.length,
      i,w;
  while(k < l){
    i = list.length;
    while(i > k){
      if(list[i-1] > list[i]){
        w = list[i-1];
        list[i-1] = list[i];
        list[i] = w;
      }
      --i;
    }
    ++k;
  }
  return list;
};
/***************************************
 * main
 ***************************************/
var before = [0,9,3,4,6,7,8,2,1,5];
console.log('before : ' + before);

var after = bubbleSort(before);
console.log('after : ' + after);

Test


/***************************************
 * sort
 ***************************************/
var bubbleSort = function(list){
  var k = 0,
      l = list.length,
      i,w;
  while(k < l){
    i = list.length;
    while(i > k){
      if(list[i-1] > list[i]){
        w = list[i-1];
        list[i-1] = list[i];
        list[i] = w;
      }
      --i;
    }
    ++k;
  }
  return list;
};
/***************************************
 * main
 ***************************************/
var before = [0,9,3,4,6,7,8,2,1,5];
console.log('before : ' + before);

var after = bubbleSort(before);
console.log('after : ' + after);

See the Pen Bubble sort algorithm in JavaScrip by Tomoyuki kashiro (@Tkashiro) on CodePen.

add ticket number to git commit automatically

Most of ticket tracker like Github, pivotal tracker have function to connect your commit to ticket(story).But every time when you commit ...… Continue reading

I will build frontend and backend separately

Published on September 28, 2016

order of angular controller's initialisation

Published on October 05, 2015