- Write a program to reverse an array using recursion.
- How to reverse an array using recursive algorithm.
Given an integer array of size N. We have to reverse given array using recursion. Reversing an array means we have to reverse the sequence of elements of array i.e 1st element will become last element and last element will become first element and so on.
For Example :
Input Array : 7 3 5 2 1 0 3 8
Reversed Array : 8 3 0 1 2 5 3 7
Algorithm to reverse an array using recursion
Let inputArray be an integer array of size N.
Let inputArray be an integer array of size N.
- To reverse inputArray, we will first swap first element(inputArray[0]) and last element(inputArray[N-1]) of inputArray and then recursively reverse subarray from index 1 to N-2.
- Let void reverseArray(int *inputArray, int leftIndex, int rightIndex); be a recursive function which reverses inputArray from index leftIndex to rightIndex. Here is the recursive equation :
reverseArray(inputArray, i, j) = reverseArray(inputArray, i+1, j-1) + swap(inputArray[i], inputArray[j]). - Recursion will terminate when leftIndex >= rightIndex.
C program to reverse an array using recursion
#include <stdio.h> void reverseArray(int *array, int leftIndex, int rightIndex){ int temp; if(leftIndex <= rightIndex){ /* Swap array element at leftIndex and rightIndex */ temp = array[leftIndex]; array[leftIndex] = array[rightIndex]; array[rightIndex] = temp; /* Recursively reverse remaining array */ reverseArray(array, leftIndex+1, rightIndex-1); } } int main(){ int array[10] = {0,1,2,3,4,5,6,7,8,9}; int i; printf("Original Array\n"); for(i = 0; i<10; i++){ printf("%d ", array[i]); } reverseArray(array, 0, 9); printf("\nReversed Array\n"); for(i = 0; i<10; i++){ printf("%d ", array[i]); } return 0; }Output
Original Array 0 1 2 3 4 5 6 7 8 9 Reversed Array 9 8 7 6 5 4 3 2 1 0