Skip to content
Jason Ghent edited this page Apr 9, 2016 · 8 revisions

Definition

Bubble 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, most of the other sorting algorithms are more efficient for large lists.

Source: Wikipedia

Code: https://github.com/felipernb/algorithms.js/blob/master/src/algorithms/sorting/bubble_sort.js

Test: https://github.com/felipernb/algorithms.js/blob/master/test/algorithms/sorting/bubble_sort.js

How to use

Import

var bubbleSort = require('algorithms').Sort.bubbleSort;

Calling

var a = [2,5,1,4,3,6,20,-10];
bubbleSort(a);
console.info(a); // [-10,1,3,4,5,6,20]

And in case a custom comparing function should be called, this Bubble Sort implementation uses a Comparator, that can be used like this:

var a = [2,5,1,4,3,6,20,-10];
// Comparator function
var reverseOrder = function (a, b) {
  if (a == b) return 0;
  return a > b ? -1 : 1;
};
bubbleSort(a, reverseOrder);
console.info(a); // [20,6,5,4,3,1,-10]
Clone this wiki locally