Reverse an Array (Iterative/Recursive)

RB07
May 8, 2021

--

  • Problem : Given an array of integers, reverse the array.
  • Example: Given input array = [4,9,8,1,3],the program should return the output as [3,1,8,9,4]
  • Solution:
  1. Iterative approach:
  • Initialize two variables left = 0 and right = (length of the given array)-1
  • In a loop, while left < right ,swap the elements at array index left and array index right. Increment left by 1 and decrement right by 1.
Iterative solution

2. Recursive approach:

  • Initialize left = 0 and right = (length of array)-1
  • Swap the elements at indices left and right
  • Recursively, call the function for rest of the array
Recursive solution

--

--

RB07
RB07

Written by RB07

0 Followers

DSA Enthusiast

No responses yet