JavaScript Algorithms: Sorting

Simple implementation of the bubble sort algorithm in JavaScript; Underscore's sortBy()

by jdcravens

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.1/underscore-min.js"></script>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<p class="result1"></p>
<p class="result2"></p>

JavaScript

var array = [3,5,2,4,7,9,6,4,5];

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

var bsortedArray = bubbleSort(array)
$('.result1').html("generic bubbleSort: " + bsortedArray)

var underscoreArray = _.sortBy(array, function(num){
    return num;
});

$('.result2').html("underscore sort: " + underscoreArray)