Reverse Array In Place Algorithm

By   Tewodros   Date Posted: Oct. 1, 2021  Hits: 852   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given an array of characters we want to reverse it in place [no extra array is allowed].

Example:

A = { 'a','b','c','d','e'};

Ans: {'e', ‘d’, ‘c’, ‘b’, ‘a’}

Solution

Here run a loop and swap the elements one from the beginning and one from the end till we reach to the center of the array. after that we don't need to do anymore since it has already swapped.

 int n = A.Length;

  for(int i=0; i<n/2;  i++)    {

               char temp = A[i];

               A[i] = A[n - i-1];

               A[n - i - 1] = temp;            

 return A;

 


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* idzril

Back to Top