### Sorting an array of numbers

The standard method of sorting in flash with myArray.sort
uses a string comparison. If you sort an array of numbers,
all numbers starting with 0 come first, then 1 and so on.
If you want numerical ordering, like 10 comes after 9 you
have to provide your own function to compare two values of
your array. Here is the example to sort numerical:
// Defining the function which does the comparison in the sort function
// The function takes two parameters a and b and returns -1 if a < b,
// 0 if a = b and 1 if a > b.
function compareNumbers( a, b){
return((a > b) - (a < b))
}
// make a new array for our test
myArray = new Array();
// fill the array with random numbers
for(i=0;i<20;i++){
myArray[i] = random(20);
}
// how does it look like unsorted ?
trace("unsorted: " add myArray);
// sort it with standard sort function
myArray.sort();
// how does it look now ?
trace("stringsorted: " add myArray);
// sort it with our numerical comparison
myArray.sort(compareNumbers);
// yes - thats what we were looking for :)
trace("numbersorted: " add myArray);

- Owen van Dijk Date: 19/11/2001

You could also use an simple Bubblesort:
function bubbleSort(inputArray, start, rest) {
for (var i = rest - 1; i >= start; i--) {
for (var j = start; j <= i; j++) {
if (inputArray[j+1] < inputArray[j]) {
var tempValue = inputArray[j];
inputArray[j] = inputArray[j+1];
inputArray[j+1] = tempValue;
}
}
}
- jupenz Date: 06/10/2003

ey... why is it that there is no result? where do i put that script? actually i am just new in here! can anyone tell me where to put the script? is it in the main time line? please help!
- maheshsangle Date: 15/12/2004

Hi,
Sorting an array of numbers works fine on its own. I m trying to capture 7 different into array. The same gets well into array; also works stupidly (string sort) till step 2 as it should.
But shows the same output even for the last step; which hopefully should be number sorted. Have u ever come across the same. Is there any email ID, where I can send the FLA just for ref.
Thankz & Regards,
Mahesh
- Flash Guy Date: 15/12/2004

Didn't work for me!
I modified the code to this;
function compareNumbers(a, b) {
return (Boolean((a-b)>0));
}
and it works fine!
- vikky Date: 28/11/2009

Hey good work nice code. Thanks!!
- Derek Date: 20/09/2010

THANK YOU! this is exactly what i have been looking for. I'm working with a vb programmer and they keep telling me to use a sort on my array of numbers but it was sorting alpha numerically.
Add comment

Home