DEV Community

theIndianDev
theIndianDev

Posted on

Reversing Array In Place

Hey, hey, hey this is my first article. Gonna keep it really short. Began learning data structures and algorithms from today. I had this thought whether is there a way to reverse an array in place without using additional space (i.e. like a new array). You guessed it right, we do have a way. This is the idea:

We are going to iterate for (N/2) times (N = length of the array) and swap the first half of the array with the second half. We are only iterating n/2 times. How cool is that, let me know what you guys think.

The Code:

class Array:
  def __init__(self):
    self.array = []
    self.length = 0

  def reverse(self):
    for i in range(len(self.array)/2):
      current_position = i
      swap_position = len(self.array) - (i + 1)

      temp = self.array[swap_position]
      current_value = self.array[current_position]
      self.array[swap_position] = current_value
      self.array[current_position] = temp

    return self.array


array = Array()
array.append(1)
array.append(2)
array.append(3)
array.append(4)
array.append(5)
array.append(6)
array.append(7)
print array.reverse() 

Top comments (0)