User Tools

Site Tools


Reversing an array

The code to reverse an array in-place iteratively is a matter of swapping elements from one end to the other. The algorithm iterates from one end of the array to the middle of the array, swapping characters $i$ and $(length-1-i)$ for a zero indexed array. This algorithm has time complexity $O(n)$ and space complexity $O(1)$.

λ reverse_an_array

The javascript built-in function a.reverse() returns a new array and does not perform an in-place reverse.

The recursive version of this algorithm is a useful study of recursion, but would not be used due to its worse performance. This algorithm has time complexity $O(n)$ and space complexity $O(n)$.

λ reverse_an_array_-_recursive

reversing_an_array.txt · Last modified: 2015/02/03 09:13 by will