loading...

Discussion on: What’s your alternative solution? Challenge #45

Collapse
miketalbot profile image
Mike Talbot

Just to point out, your algorithm presented doesn't actually bubble making it much slower. In a bubble sort we guarantee that one element bubbles to the end of the list. We never need to consider it again. So while that bubbling will happen to the array elements in your code, we never get the benefit of it.


var ar = [23, 1000, 1, -1, 8, 3];
println(ar);
bubbleSort(ar);
println(ar);

function bubbleSort(ar)
{
    var shouldSort = true;
    var length = ar.length;

    while(shouldSort)
    {
        shouldSort = false;
        length--;
        for(var i = 0; i < length; i++)
        {
            var a = ar[i];
            if ( a > ar[i+1] )
            {
                ar[i] = ar[i+1];
                ar[i+1] = a;
                shouldSort = true;
            }
        }
    }
}