Ludicrous Software

Flash Lite 1.1 Array Sorting

The question of how to sort emulated arrays came up on one of the Flash Lite email lists, so I thought I’d post my solution here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// fake array
p1 = 5;
p2 = 3;
p3 = 6;
p4 = 2;
p5 = 9;
arrayLength = 5;
// sort
for (outer = 1; outer < arrayLength; outer++) {
    for (inner = outer + 1; inner <= arrayLength; inner++) {
        if (eval("p" add inner) > eval("p" add outer)) {
            tempVal = eval("p" add outer);
            eval("p" add outer) = eval("p" add inner);
            eval("p" add inner) = tempVal;
        }
    }
}
// show results
for (i = 1; i <= arrayLength; i++) {
    trace(eval("p" add i));
}

The code is pretty straightforward - basically you’re just looping through each value in the array, comparing that value to all of the other values in the array. If another value is larger, you swap the two values. The result is an array sorted from highest value to lowest. If you want to sort from lowest to highest, simply change the ‘greater than’ in the if() statement to a ‘less than’, and you’re good to go.

One thing to be careful of is if you’re sorting a very large number of values. The nested for loops can result in a large number of iterations, and could cause your movie to hang. If that happens, simply break the code over multiple frames, using counters and conditionals to iterate through the array.