bigjocker's den

Implementing robsort() in Javascript

Reading on Google+ I saw a post by Rob Malda describing a very inefficient sorting algorithm he designed while in college. The gist of the algorithm is:

while my numbers are out of order, swap two of them at random.

But how inefficient is it? Well, here’s a simple javascript implementation.

Just enter some integers in the input field separated by spaces and click Go!. My browser is still trying to sort an array with 15 digits. Here’s how it works:

run = 0;
function robsort(a, where) {
        run++;
        r = Math.floor(Math.random() * (a.length - 1));
        aux = a[r];
        a[r] = a[r + 1];
        a[r + 1] = aux;

        printArray(a, where);
        document.getElementById('run').innerHTML = run;
        if (!isSorted(a)) {
                 document.getElementById('status').innerHTML = 'Sorting ...';
                 setTimeout(function() {robsort(a, where)}, 1);
        } else {
                 document.getElementById('status').innerHTML = 'Sorted!!!!';
        }
}
So proud. Next I’m going to implement ROT-26.5.

Leave a Reply

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