Tim Walling

AS2 Sorting Algorithms

I've come across various sorting algorithms a few times and have wanted to see how they perform in Flash. Recently I came across this list of algorithms and thought I'd finally play around with them.

The above sorting functions were written in java so I converted them to actionscript and created a test swf below. Create a test array by entering a number, say 1000 for example, then run a sort on the array. The array that's generated consists of random numbers between 1 - 250 and the sorting algorithms sort the array from lowest to highest. Note, I didn't include the Quick Sort algorithm because its too recursive and Flash complains. It's not as quick as some of the other algorithms anyway so no big loss. I also had to grab the Shell Sort from Wikipedia since the one I found above goes into an endless while loop. Typo in the example or just a bad conversion on my part? I'm not sure.

[![Get Adobe Flash player](http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif)](http://adobe.com/go/getflashplayer)

Overall the Insertion Sort seems to be the most efficient. I've included the source code for the sorting algorithms here:

Sorting.zip

I'm going to play around with these some more and make some modifications to the class so that you can pass in more complex arrays and specify which property you'd like to sort by, add ascending vs descending, etc.

Update: The following code example was posted by Felix, it just didn't make it in the comment form.

function gnomeSort(ar:Array):Void {
    var i:Number = 0;
    var n:Number = ar.length;
    var tmp;

    while (i < n) {
        if (i == 0 || ar[i-1] <= ar[i]) {
            i++;
        } else {
            tmp = ar[i];
            ar[i] = ar[i-1];
            ar[--i] = tmp;
        }
    }
}