Ultrashock Forums > Flash > ActionScript
Share Data Structures & Algorithms

You are currently viewing our website as a guest which gives you limited access to forums, files and other resources.

Click here to join now for free, and start interacting with our members, download files and much more!

Click here if you are looking for our Flash files and other professional assets.
 
Post Reply | View first unread | Rate Thread Search this Thread | Thread Tools | Display Modes

#1
Bookmark and Share!
Share Data Structures&Algorithms
Old 2005-04-05

I’ve just begun to convert a number of DS&A from Java into AS2 and it got me thinking...

I’m sure others have some they have used/developed. It would be great if we could gather them together in a thread for other developers to learn from/use. This will also give the chance for others to suggest possible improvements.

To keep code easily referenced and readable, it would be good if we could follow a format similar to this
-----------
Title: Name of DS or A (if an optimized version of one already posted, then indicate this)
1: (Optional) Overview of DS or A
2: Code dump
3: How to use it
4: (Optional) Further examples of use
when in doubt, leave it out - Josh Bloch
postbit arrow 7 comments | 2636 views postbit arrow Reply: with Quote   
Moderator
Mike is offline Moderator
seperator
Posts: 2,191
2003-12-25
Age: 28
Mike lives in United Kingdom
Mike's Avatar
seperator

Ultrashock Member Comments:
Mike's Avatar Mike Mike is offline Moderator Mike lives in United Kingdom 2005-04-05 #2 Old  
Quick Sort
Last edited by Mike : 2006-06-11 at 04:32.
Note I've not been able to beat the built in performance of Array.sort or Array.sortOn functions (unsurprisingly I guess) which I'm sure both use a quicksort, so this is really for you geeks who want to study/play with it.

Sort algorithm using divide-and-conquer technique. Array is partitioned into 3 segments, left (west), middle (pivot) and right (east). The pivot segment contains only one element. No element on to the left of the pivot contains a key larger than the pivot, and no element on the right of the pivot contains a key less than the pivot. Now we sort left and right partitions using recursive quick sort.
ActionScript Code:
  1. QuickSort
  2. {
  3.     private function QuickSort(){}
  4.    
  5.     // a = array to be sorted
  6.     // param = parameter to sort on (must hold a num or string)
  7.     public static function sort(a:Array, p:String):Void
  8.     {
  9.         if(a == undefined || a.length <= 1) {
  10.             return;
  11.         }
  12.        
  13.         // Only done simple checking
  14.         if(p != undefined && (typeof(a[0][p]) == "string" ||
  15.                 typeof(a[0][p]) == "number" || typeof(a[0][p]) == "boolean")) {
  16.           doObjSort(a, 0, a.length - 1, p);
  17.         }
  18.         else if(typeof(a[0]) == "string" || typeof(a[0]) == "number" ||
  19.                                         typeof(a[0]) == "boolean") {
  20.           doPrimSort(a, 0, a.length - 1);
  21.         }
  22.     }
  23.    
  24.     // Note: Recursively passing in "a" and "p" appears faster
  25.     // than setting them as a class property.
  26.     // we/ee = west/east end
  27.     // wc/ec = west-east/east-west cursor
  28.     // Recursive quick sort on property p of object array
  29.     private static function doObjSort(a, we:Number, ee:Number, p):Void
  30.     {
  31.         var wc:Number = we;
  32.         var ec:Number = ee;
  33.         var pivot:Object = a[Math.round((we+ee)/2)][p];
  34.         var t:Object;
  35.  
  36.         while (true)
  37.         {
  38.             while (a[wc][p] < pivot) wc++;
  39.             while (a[ec][p] > pivot) ec--;
  40.             if (wc > ec) {break;}// not pretty but seems quicker
  41.             t = a[wc];
  42.             a[wc++] = a[ec];
  43.             a[ec--] = t;
  44.         }
  45.         if(we < ec) doObjSort(a, we, ec, p);
  46.        if(ee > wc) doObjSort(a, wc, ee, p);
  47.     }
  48.    
  49.     // Recursive quick sort on array of primitives
  50.     private static function doPrimSort(a, we:Number, ee:Number):Void
  51.     {
  52.         var wc:Number = we;
  53.         var ec:Number = ee;
  54.         var pivot:Object = a[we];
  55.         var t:Object;
  56.        
  57.         while (true)
  58.         {
  59.             while (a[wc] < pivot) wc++;
  60.             while (a[ec] > pivot) ec--;
  61.             if (wc > ec) {break;}
  62.             t = a[wc];
  63.             a[wc++] = a[ec];
  64.             a[ec--] = t;
  65.         }
  66.      if(we < ec) doPrimSort(a, we, ec);
  67.        if(ee > wc) doPrimSort(a, wc, ee);
  68.     }
How to use it:
ActionScript Code:
  1. // Can be an array of Boolean, String or Numeric values
  2. var numArray:Array = new Array(2,5,3,6,8,5,3,59,87,23,4,634);
  3. QuickSort.sort(numArray);
  4. trace(numArray); // Gives: 2,3,3,4,5,5,6,8,23,59,87,634
  5.  
  6. // You can also sort on an array of common objects by one
  7. // of their properties, as long as this property is of type
  8. // Boolean, String or Number. For instance, if you had an
  9. // array of MovieClips "clipArray" you could sort these
  10. // on their names like so:
  11.  
  12. QuickSort.sort(clipArray, "_name");

If you linked this up with the Layout class and related classes I posted in this thread(with help from Rampage & senocular)(second large code dump half way down) and added some tweening to the arrange functions:
http://<a href="http://www.ultrashoc...adid=66958</a>
You could create something along the lines of product sort here:
http://www.crew9.net/flash.html
Reply With Quote  
Mike's Avatar Mike Mike is offline Moderator Mike lives in United Kingdom 2005-04-05 #3 Old  
Array Queue
FIFO Queue (simple but worth a post)
ActionScript Code:
  1. // Generic Queue Interface
  2. interface IQueue
  3. {
  4.    public function peek():Object
  5.    public function dequeue():Object
  6.    public function enqueue(element:Object):Void
  7.    public function isEmpty():Boolean
  8. }
ActionScript Code:
  1. class ArrayQueue implements IQueue
  2. {
  3.    var queue:Array;
  4.  
  5.    public function ArrayQueue(initCapac:Number)
  6.    {
  7.        if(initCapac == undefined || initCapac <= 0) {
  8.            queue = new Array();
  9.        }
  10.        else {queue = new Array(initCapac);}
  11.    }
  12.  
  13.    // Return front of queue but don't remove it
  14.    public function peek():Object
  15.    {
  16.       if (isEmpty()) {return null;}
  17.       return queue[queue.length-1];
  18.    }
  19.    
  20.    // Remove and return front element of queue
  21.    public function dequeue():Object
  22.    {
  23.       if (isEmpty()) {return null;}
  24.       return queue.pop();
  25.    }
  26.    
  27.    // Insert element at the rear of queue
  28.    public function enqueue(element:Object):Void
  29.    {queue.unshift(element);}
  30.    
  31.    // Check if queue is empty
  32.    public function isEmpty():Boolean
  33.    {return !queue.length;}
  34.    
  35.    public function toString():String
  36.    {return queue.toString();}
  37. }
How to use it:
ActionScript Code:
  1. // Example...
  2. var q:ArrayQueue = new ArrayQueue();
  3. trace("empty "+q.isEmpty()); // empty true
  4. q.enqueue("A");
  5. q.enqueue("B");
  6. q.enqueue(1);
  7. q.enqueue(2);
  8.  
  9. trace("queue "+q); // queue 2,1,B,A
  10. trace("peek "+q.peek()); // peek A
  11. trace("dequeue "+q.dequeue()); // dequeue A
  12. trace("queue "+q); // queue 2,1,B
  13. q.enqueue("X");
  14. trace("queue "+q); // queue X,2,1,B
  15.  
Reply With Quote  
Mike's Avatar Mike Mike is offline Moderator Mike lives in United Kingdom 2005-04-05 #4 Old  
Flash Sort
I converted a Java example found at the site bellow and I believe it is correct. From tests the Quick Sort seems WAY faster than the Flash Sort when it comes to an array of strings (at any size), but when it comes to larger arrays (300+) of numbers, FlashSort wins. As the array size increases, so does the performance gap between the two. (Oh, and the name Flash Sort has nothing to do with MM Flash! )

Find out more about this sort here: http://www.neubert.net/Flacodes/FLACodes.html
ActionScript Code:
  1. /**
  2. * Translation of Karl-Dietrich Neubert's algorithm into AS2.0   
  3. * Conversion made from Rosanne Zhang's Java code
  4. */
  5. class FlashSort
  6. {
  7.     public static function sort(a:Array):Void
  8.     {
  9.         stageOneFlashSort(a);
  10.         stageTwoInsertionSort(a);
  11.     }
  12.  
  13.     private static function stageOneFlashSort(a:Array):Void
  14.     {
  15.         var n = a.length;
  16.        
  17.         //Number of groups into which the elements are classified
  18.       //Neubert suggests 0.2 to 0.5 times the number of elements in the array.
  19.         var m = Math.round(n*0.3);
  20.         if(m <= 0 ) m = 1;
  21.         var l = new Array(m);
  22.         var i = 0, j = 0, k = 0;
  23.         var anmin = a[0];
  24.         var nmax  = 0;
  25.         for(var x = 0; x<m; x++) l[x]=0; // init vector values
  26.         for (i=1; i < n; i++)
  27.         {
  28.             if (a[i] < anmin) anmin=a[i];
  29.             if (a[i] > a[nmax]) nmax=i;           
  30.         }
  31.  
  32.         if (anmin == a[nmax]) return;
  33.         var c1 = (m - 1)/(a[nmax] - anmin);
  34.  
  35.         for (i=0; i < n; i++)
  36.         {
  37.             k=Math.round(c1*(a[i] - anmin));
  38.             l[k]++;
  39.         }
  40.  
  41.         for (k=1; k < m; k++)
  42.         {
  43.           l[k] += l[k-1];
  44.         }
  45.  
  46.         var hold = a[nmax];
  47.         a[nmax]=a[0];
  48.         a[0]=hold;
  49.  
  50.         var nmove = 0;
  51.         var flash;
  52.         j=0;
  53.         k=m-1;
  54.  
  55.         while (nmove < n-1)
  56.         {
  57.             while (j > (l[k]-1))
  58.             {
  59.                 j++;
  60.                 k = Math.round(c1 * (a[j] - anmin));
  61.             }
  62.             flash = a[j];
  63.            
  64.             //
  65.             while (j != l[k])
  66.             {
  67.                 k = Math.round(c1 * (flash - anmin));
  68.                 hold = a[l[k]-1];
  69.                 a[l[k]-1]=flash;
  70.                 flash = hold;
  71.                 l[k]--; // dec pointer to next index
  72.                 nmove++;
  73.             }
  74.         }
  75.     }
  76.    
  77.     // Now we have our partially ordered array,
  78.     // we do an insertion sort to order the remainder.
  79.     private static function stageTwoInsertionSort(a:Array):Void
  80.     {
  81.         var i:Number;
  82.         var j:Number;
  83.         var h:Number;
  84.        
  85.         for (i=a.length-3; i>=0; i--)
  86.         {
  87.             if (a[i+1] < a[i]) {
  88.                 h = a[i];
  89.                 j=i;
  90.                 while (a[j+1] < h)
  91.                 {
  92.                     a[j] = a[j+1];
  93.                     j++;
  94.                 }
  95.                 a[j] = h;
  96.             }
  97.         }
  98.     }
  99. }
How to use it:
ActionScript Code:
  1. // Recommend using FlashSort only on large (300+) array of nums
  2. // QuickSort otherwise
  3. var numArray:Array = new Array(2,5,3,6,8,5,3,59,87,23,4,634);
  4. FlashSort.sort(numArray);
  5. trace(numArray); // Gives: 2,3,3,4,5,5,6,8,23,59,87,634
  6.  
Reply With Quote  
Mike's Avatar Mike Mike is offline Moderator Mike lives in United Kingdom 2005-06-19 #5 Old  
Binary Search (Divide and Conquer)
Last edited by Mike : 2007-04-02 at 11:34.
Updated to use bitwise shift to half and floor m, cheers Nutrox

This may well be floating about Ultrashock somewhere, but I couldn’t find it. Anyway, this is (divide and conquer) binary search on an array sorted in ascending order. This is obviously a lot faster than a sequential search (on average). If you have not come across this before and wish to find out more, you can Google it for loads of result.

AS2 Version
ActionScript Code:
  1. class BinarySearch
  2. {
  3.     private function BinarySearch(){}
  4.    
  5.     public static function search(a:Array, x:Object):Number
  6.     {
  7.         if(a == undefined || x == undefined) return -1;
  8.         var m, w = 0, e = a.length;
  9.         while(w<=e) {
  10.             m = (w+e) >> 1;
  11.             if(x == a[m]) return m;
  12.             if(x < a[m]) e = m-1;
  13.             else w = m+1;
  14.         }
  15.         return -1;
  16.     }
  17. }
How to use it:
ActionScript Code:
  1. var resultIndex:Number = BinarySearch.search(sortedArray, searchValue);
Array.prototype version
ActionScript Code:
  1. Array.prototype.binarySearch = function(x) {
  2.     if(x == undefined) return -1;
  3.     var m, w = 0, e = this.length;
  4.     while(w<=e) {
  5.         m = (w+e) >> 1;
  6.         if(x == this[m]) return m;
  7.         if(x < this[m]) e = m-1;
  8.         else w = m+1;
  9.     }
  10.     return -1;
  11. }
How to use it:
ActionScript Code:
  1. var resultIndex:Number = sortedArray.binarySearch(searchValue)
Reply With Quote  
Codemonkey's Avatar Codemonkey Codemonkey is offline Super Moderator Codemonkey lives in Netherlands 2006-06-11 #6 Old  
Very cool, Mike. Could you maybe create some fictional scenarios where you would specifically pick one of these? I never have the feeling like "hmm, binary search would really speed things up here" (and what about hashtables, splay trees, HOT queues and whatnot?).
Reply With Quote  
Nutrox's Avatar Nutrox Nutrox is offline Super Moderator Nutrox lives in United Kingdom 17 Creative Assets 2006-06-11 #7 Old  
Yar, very nice.

I assume, in Layman's terms, that "Data Structures & Algorithms" simply means "utility classes"... unless I've missed something.

Either way, I've made this thread sticky because it looks like it will end up being a good resource.
Reply With Quote  
Mike's Avatar Mike Mike is offline Moderator Mike lives in United Kingdom 2006-06-11 #8 Old  
Cheers Nutrox,

They do fall under the umbrella of util classes. Data structures encapsulating a specific collection of data and operations allowed on them. Algorithms providing some sort of working on data structures.

Of course there are hundreds more data structures and algorithms out there. I haven't had the need for all of them in Flash just yet. Although it's always good to view the inner workings I think.

I hope others feel free to post more (or other versions) so we can build up a nice collection.

As for scenarios, well each algorithm has it's own forte. I've posted, along with each algorithm, where and on when it is useful.

Data structures I use when I want to hide operations I'm doing on a collection and help clarify my code (for hash table I tend to use a native object as it's pretty much how I would want it).
Reply With Quote  
Thread Tools
Display Modes Rate This Thread
Rate This Thread: