Bubble Sorts

There is no reason to EVER use a Bubble sort.

by james young

HTML

<div>Sorted Array: <span id="result"></span></div>

<div>Loop Count: <span id="loopcount"></span></div>

<div>Toggle the comment from line 17 to 18 to see the difference in Loop Count.</div>

CSS

div { padding-top: 1em; }

JavaScript

var unsortedArray = [10, 7, 45, 2, 8, 9, 1],
    loopcountElement = document.getElementById('loopcount');

function bubbleSort(data) {
    var length = data.length,
        loopCounter = 0,
        lastSwap = length,
        count = length,
        temp,
        i,
        j;
    
    for (i = 0; i < length; i++) {
        loopCounter++;
        lastSwap = 1;
        
        for (j = 1; j < length; j++) {
//        for (j = 1; j < count; j++) {
            loopCounter++;

            if (data[j] < data[j - 1]) {
                temp = data[j];
                data[j] = data[j - 1];
                data[j - 1] = temp;
                lastSwap = j;
            }
        }
        
        count = lastSwap;
    }
    
    loopcountElement.innerHTML = loopCounter;
    
    return data;
}

document.getElementById('result').innerHTML = JSON.stringify(bubbleSort(unsortedArray));


/*
bubbleSort(array A) {
   n = length(A);
   for(j = 0; j < n; j++){         <----- THIS LINE IS WRONG
       lastswap = 1;
       for(i = 1; i < j; i++) {    <----- THIS LINE IS WRONG
         if A[i-1] > A[i] {
             swap(A[i-1], A[i]);
             lastswap = i;
       }        
       n = lastswap;
    }
}
*/