Posted by: Yogesh Puri on: August 18, 2008
I was studying Data Structure book last week and have converted some C based sorting Algorithms into AS3. The code is quite slow as compared to Flash Player’s internal sorting algorithms however just for an example purpose i have written this code
Following are 3 algorithms those i have converted. All these 3 are not one of the fastest however Fastest ones are in queue and will be up soon
Bubble Sort : Exchange two adjacent elements if they are out of order. Repeat until array is sorted. This is a slow algorithm.
Selection Sort : Find the largest element in the array, and put it in the proper place. Repeat until array is sorted. This is also slow.
Insertion Sort : Scan successive elements for out of order item, then insert the item in the proper place. Sort small array fast, big array very slowly.
Following is code for Bubble sort and rest you can download from here
package com.utils.Algo
{
import flash.display.Sprite;
/**
* ...
* @author Yogesh Puri
*/
public class BubbleSort extends Sprite
{
public function BubbleSort()//Bubble sort function
{
}
public function sort(_arr: Array)
{
var iLen:uint = _arr.length;
var i, j, temp: uint;
for(i=0;i<iLen;i++) {
for(j=0;j_arr[j])
{
temp =_arr[i]; //swap
_arr[i]=_arr[j];
_arr[j]=temp;
}
}
}
}
public function printElements(_arr:Array) //print array elements
{
var iLen:uint = _arr.length;
for(var i:uint=0;i<iLen;i++)
trace(_arr[i]);
}
}
}
[...] – bookmarked by 4 members originally found by mew1157 on 2008-09-21 Sorting Algorithm in AS3 http://flexcomps.wordpress.com/2008/08/18/sorting-algorithm-in-as3/ – bookmarked by 4 members [...]
Actually, AS3 sorting can be as much as 5 times faster than Flash Player’s internal sort algorithm: http://www.valveblog.com/2009/06/as3-sorting-algorithm-faster-than-native-sorting.html
August 18, 2008 at 9:16 am
In most cases, the built-in sort should be fine.
And when it’s not adequate, forget bubble sort and the like – they may be simple, but horribly inefficient.
See Quicksort http://en.wikipedia.org/wiki/Quicksort
If you understand recursivity, implementing it in AS3 is trivial.