DEV Community

theIndianDev
theIndianDev

Posted on

2 3

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() 

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay