Reversing an array with swaps

Arielle Sullivan
4 min readApr 28, 2014

To reverse an array in place, I first implemented a basic loop that pops the last element and inserts it at the front of the array at an index that increments throughout the loop. To start I’ll initialize a class using an example array as an instance variable.

A for loop the length of the array can help determine the index where the last element gets inserted. The insert method takes two arguments, the index at which to insert and the element that is being inserted.

I then added this into my ReverseArray class.

Another way to approach this would be to swap the first element with the last, the second with the penultimate, etc. until the entire array is reversed. To begin this approach, let’s define the left (front) swapper and the right (back) swapper.

Next, we start the swaps. An until loop can be used to stop swapping once the left and right swappers converge.

To maintain single responsibility, the swap can be done in a separate instance method. To avoid passing the swappers explicitly to that method, we can set the left and right swappers as instance variables. I have left space for a ‘swap’ method in the code below

In the swap method, we will do two things. First, make the swap. Then, redefine the swappers to the next in line. Assuming we will use the swappers’ indices throughout this process, let’s define them in variables.

#do the swap

If the left swapper is swopped with the right then the original value of the left swapper is now lost and the right swapper has nothing to swap with. (Tongue twister!) To avoid this dilemma we can store the left swapper in a variable temporarily. I call this variable ‘storage’. The right swapper will then be able to swap with the left value even after the left has been swapped. The code says it best:

The left swapper begins as “a” at index 0.

The right swapper is “d” at index 3.

Storage is then equal to “a”.

@array[0] is then set to be “d”.

The left swapper has now been replaced with “d” so the right swapper turns to ‘storage’ to set @array[3] with “a”.

#redefine swappers

Last, we must now reset the swappers to the next in the array that remain untouched. We can do this increasing the index of the left swapper (moving it one to the right) and decreasing the index of the right swapper (moving one to the left).

We now have two methodologies to reverse an array. Let’s benchmark each to see which is more efficient!

We can require ‘benchmark’ at the top of the file and add the following lines below the class. These lines will then be printed when we run the operation from the terminal.

I ran the operation above with a slightly larger array to make the difference in time between the two methods clearer. The reverse with a swap is faster!

--

--