Objective: Given a array, write an algorithm to reverse the array.
Example:
int a[] = {1, 2, 3, 4, 5} Output: {5, 4, 3, 2, 1}
Approach:
- It’s obvious that you cannot use any built-in function reverse it.
- It’s a simple solution, we will solve it using recursive and non-recursive way.
- Take 2 elements at a time, one from the from start and one from the end and swap them.
- Now for recursion, Make a recursive call to rest of the string and for non-recursive solution, use the for loop and swap the elements start +1 and end +1.
Code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class ReverseArray { | |
static int [] a; | |
public static void reverseIteration(){ | |
int start =0; | |
int end = a.length–1; | |
while(start<=end){ | |
int temp = a[start]; | |
a[start] = a[end]; | |
a[end] = temp; | |
start++; | |
end—; | |
} | |
} | |
public static void reverseRecursive(int start, int end){ | |
if(start<=end){ | |
int temp = a[start]; | |
a[start] = a[end]; | |
a[end] = temp; | |
start++; | |
end—; | |
reverseRecursive(start, end); | |
} | |
} | |
public static void main(String[] args) { | |
a = new int []{1,2,3,4,5}; | |
System.out.println("Original Array" + Arrays.toString(a)); | |
reverseIteration(); | |
System.out.println("Reversed – Array(Iteration):" + Arrays.toString(a)); | |
reverseRecursive(0,a.length–1); | |
System.out.println("Reversed Again – Array(Recursion):" + Arrays.toString(a)); | |
} | |
} |
Output:
Original Array[1, 2, 3, 4, 5] Reversed - Array(Iteration):[5, 4, 3, 2, 1] Reversed Again - Array(Recursion):[1, 2, 3, 4, 5]
Thanks for sharing this program. Here is an alternate C program to reverse an array using recursion.
package datastructues;
public class ReverseArray {
static int[] a = new int[] { 1, 2, 3, 4, 11, 10, 5, 6, 7, 8 };
public static void main(String[] args) {
for(int k = a.length-1; k>=0; k–)
{
System.out.println(a[k]);
}
recurse(a, a.length -1);
int[] reverseArray = reverseArray(a);
System.out.println(reverseArray);
}
private static void recurse(int[] a, int total) {
if(total >= 0)
{
System.out.println(a[total]);
recurse(a, –total);
}
}
private static int[] reverseArray(int[] a)
{
for (int i = 1; i <= a.length / 2; i++) {
a[i-1] = a[i-1] + a[a.length-i];
a[a.length-i] = a[i-1] – a[a.length-i];
a[i-1] = a[i-1] – a[a.length-i];
}
return a;
}
}