Last active
December 11, 2015 07:49
-
-
Save a-r-d/4568953 to your computer and use it in GitHub Desktop.
AS3- using quick sort algorithm to sort on an arbitrarily specified attribute of a typed vector.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Some constants we use to choose sorting methods. | |
*/ | |
public static const SORT_BY_DATE_START:String = "DATE_START"; | |
public static const SORT_BY_ID_ASC:String = "ID_ASC"; | |
/** | |
* Example function that calls the quick sort on a vector of some beans | |
*/ | |
public static function getTopLevelTasks( taskList:Vector.<Task2>, sortBy:String = SORT_BY_ID_ASC ):Vector.<Task2> { | |
var topLevelTasks:Vector.<Task2> = new Vector.<Task2>(); | |
for( var i:int = 0; i < taskList.length; i++) { | |
if( taskList[i].parentTaskID == 0 || taskList[i].parentTaskID == -1) { | |
topLevelTasks.push( taskList[i] ); | |
} | |
} | |
if( sortBy == SORT_BY_DATE_START ) { | |
topLevelTasks = vectorQuickSortByAttr( topLevelTasks, "dateStart" ); | |
} else if( sortBy == SORT_BY_ID_ASC ) { | |
topLevelTasks = vectorQuickSortByAttr( topLevelTasks, "task_id" ); | |
} | |
return topLevelTasks; | |
} | |
/*** | |
* Wamp wamp implement quick sort... | |
*/ | |
public static function vectorQuickSortByAttr(tosort:Vector.<Task2>, sortAttr:String):Vector.<Task2> { | |
if( tosort.length <= 1) | |
return tosort; | |
var pivot_index:int = Math.round(Math.random() * (tosort.length - 1)); | |
var pivot:Task2 = tosort[ pivot_index ]; | |
// remove pivot from the vector: | |
tosort.splice(pivot_index, 1); | |
var l_list:Vector.<Task2> = new Vector.<Task2>(); | |
var g_list:Vector.<Task2> = new Vector.<Task2>(); | |
for( var i:int = 0; i < tosort.length; i++ ) { | |
if( tosort[i][sortAttr] > pivot[sortAttr] ) { | |
g_list.push( tosort[i] ); | |
} else { | |
l_list.push( tosort[i] ); | |
} | |
} | |
// return l_list + pivot + g_list | |
l_list.push( pivot ) | |
return l_list.concat( g_list ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment