How to reverse an array with ActionScript (without the .reverse method)
I was reading a blog the other day and in it the author mentioned the fact that a lot of programmers don’t know how to reverse an array in their language of choice. Not by using a library or language method like we have in ActionScript but the acutal programmatic task of reversing an array.
I have used the handy reverse method in the past but never really thought much about how it acutally worked. Not being a CS major and coming from more of a Multimedia background I thought that this would be something to look into.
Here is the code to do the reverse operation:
function reverse(a) {
// index of leftmost element
var left = 0;
// index of rightmost element
var right = a.length-1;
while (left < right) {
// exchange the left and right elements
var temp = a[left];
a[left] = a[right];
a[right] = temp;
// move the bounds toward the center
left++; right–;
}
}
var example_array = new Array(1,2,3,4,5);
trace(example_array);
reverse(example_array);
trace(example_array);
This is Java code ported to ActionScript the original Java code can be found here:
http://www.leepoint.net/notes-java/data/arrays/34arrayreverse.html
Here is how you use the reverse method in ActionScript if you are looking or wondering: Array.reverse();
4 Comments so far
Leave a reply


or if you’re stuck in AS1 land.
var example_array = new Array(1,2,3,4,5);
trace(example_array);
example_array.reverse();
trace(example_array);
I found that you have to return the array that is passed in the function callback
function reverse(_arr):Array{
var left:Number = 0;
var right:Number = _arr.length-1;
while(left
I am trying to reverse the array of an xml file so that if you add a new element to the top of the xml file it will load in reverse order in a list component. is this possible?
[...] If you remember back about a year ago now you may recall seeing an algorithm posted on the ActionScript Cheatsheet blog demonstrating how to reverse an Array. There was a distance learning course on UWTV on the C programming langauge and an unrelated blog post that prompted my interest in the reverse algorithm. Recently I was asked about an algorithm to “guess” an integer within a given range. Something about that old reverse algorithm instantly met my mind. The whole left, right, mid concept in particular. [...]