Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Reverse the given Array without using built in function

Objec­tive: Given a array, write an algo­rithm to reverse the array.

Exam­ple:

int a[] = {1, 2, 3, 4, 5}
Output: {5, 4, 3, 2, 1}

Approach:

  • It’s obvi­ous that you can­not use any built-in func­tion reverse it.
  • It’s a sim­ple solu­tion, we will solve it using recur­sive and non-recursive way.
  • Take 2 ele­ments at a time, one from the from start and one from the end and swap them.
  • Now for recur­sion, Make a recur­sive call to rest of the string and for non-recursive solu­tion, use the for loop and swap the ele­ments start +1 and end +1.

Code:

Out­put:

Original Array[1, 2, 3, 4, 5]
Reversed - Array(Iteration):[5, 4, 3, 2, 1]
Reversed Again - Array(Recursion):[1, 2, 3, 4, 5]

You may also like...