Friday Algorithms: JavaScript Bubble Sort

Bubble Sort

Unsorted Array

This is one of the most slowest algorithms for sorting, but it’s extremely well known because of its easy to implement nature. However as I wrote past Fridays there are lots of sorting algorithms which are really fast, like the quicksort or mergesort. In the case of bubble sort the nature of the algorithm is described in its name. The smaller element goes to the top (beginning) of the array as a bubble goes to the top of the water.

There is a cool animation showing how bubble sort works in compare to the quick sort and you can practically see how slow is bubble sort because of all the comparing.

QuickSort vs. BubbleSort

Pseudo Code

Actually what I’d like to show you is how you can move from pseudo code to code in practice. Here’s the pseudo code from Wikipedia.

procedure bubbleSort( A : list of sortable items ) defined as:
  do
    swapped := false
    for each i in 0 to length(A) - 2 inclusive do:
      if A[i] > A[i+1] then
        swap( A[i], A[i+1] )
        swapped := true
      end if
    end for
  while swapped
end procedure

JavaScript Source

var a = [34, 203, 3, 746, 200, 984, 198, 764, 9];
 
function bubbleSort(a)
{
    var swapped;
    do {
        swapped = false;
        for (var i=0; i < a.length-1; i++) {
            if (a[i] > a[i+1]) {
                var temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
                swapped = true;
            }
        }
    } while (swapped);
}
 
bubbleSort(a);
console.log(a);

As a result you’ve a sorted array!

Sorted Array

8 thoughts on “Friday Algorithms: JavaScript Bubble Sort

  1. after your while statement, use

    for(i=0;i&lt;a.length;i++)
    {
        document.write(a[i]+&quot; ` &quot;);
    }

    it should help to compare the array.

  2. Thanks, saved me the trouble of doing it myself. Quick note – should probably declare the temp variable as private outside of the loop:

    var swapped, temp;

  3. Hooray for “Bubble Sorting”. Here’s the way I write them in Javascript:

    var arr = [9, 2, 1, 3, 0, 8, 7, 6, 5, 4, 10];

    function bubbleSort(theArray) {
    var i, j;
    for (i = theArray.length – 1; i >= 0; i–) {
    for (j = 0; j <= i; j++) {
    if (theArray[j + 1] < theArray[j]) {
    var temp = theArray[j];
    theArray[j] = theArray[j + 1];
    theArray[j + 1] = temp;
    }
    }
    }
    return theArray;
    }

    console.log(bubbleSort(arr));

  4. var numbers = [7,623,53,1,582,928];

    function bubbleSort() {
    numbers.sort(function(a, b){return a-b});
    console.log(numbers);
    }

    bubbleSort();

  5. var arr = [1, 6, 9, 2, 10, 34, 66, 3];

    for(var i = 0; i < arr.length – 1; j++) {
    for(var j = 1; j arr[j]) {
    var t = arr[j];
    arr[j] = arr[j – 1];
    arr[j – 1] = t;
    }
    }
    }

    console.log(arr);

Leave a Reply

Your email address will not be published. Required fields are marked *