all groups > flash actionscript > october 2004 >
You're in the

flash actionscript

group:

How do I sort a linear numerical array


How do I sort a linear numerical array loop360
10/3/2004 5:49:46 PM
flash actionscript:
Can anyone tell me how to sort a linear numerical array?

I have an array like myArray = [9,21,3,4,19] but if I try and sort the array
like myArray.sort, it comes out like (19, 21,3,4,9)? I have looked at sortOn()
but you need an element name which I don't have in this array - can anyone help
me?

Cheers!
Re: How do I sort a linear numerical array inhswebdev
10/3/2004 6:06:30 PM
When ever I need to sort arrays; I used the following. Hope this helps, let me
know if you have any questions :). This uses the array that you supplied and
orders the numbers.

var myArray = new Array(9,21,3,4,19);

trace("Before quick sort");
for(i = 0; i < myArray.length; i++) {
trace(myArray);
}

quickSort(0, i - 1);

trace("After quick sort");
for(i = 0; i < myArray.length; i++) {
trace(myArray);
}

/*************************************\
Quick sort algorithm to quickly
sort arrays.
\*************************************/
function quickSort(low, high){
if(low < high){
pivot = partition(low, high);
quickSort(low, pivot - 1);
quickSort(pivot + 1, high);
}
}
/*************************************\
partition fuction used by quick
sort, returns the new pivot point
\*************************************/
function partition(low, high) {
p_pos = low;
pivot = myArray[p_pos];
for(i = low + 1; i <= high; i++) {
if(myArray < pivot) {
p_pos++;
swap(p_pos, i);
}
}
swap(low, p_pos);
return p_pos;
}
/*************************************\
swap function that gets the corect
item into position.
\*************************************/
function swap(left, right) {
temp = myArray[left];
myArray[left] = myArray[right];
myArray[right] = temp;
return true;
}
AddThis Social Bookmark Button