Java Online Compiler
Example: Array Reversal using Recursion in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Array Reversal using Recursion import java.util.Arrays; // Required for printing the array easily // Main class containing the entry point of the program public class Main { // Recursive function to reverse an array public static void reverseArrayRecursive(int[] arr, int start, int end) { // Step 1: Base Case - If start index is greater than or equal to end index, // it means the sub-array has one or zero elements, or we've crossed over, // so no more swaps are needed. if (start >= end) { return; } // Step 2: Swap elements at the start and end positions int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; // Step 3: Recursive Call - Call the function for the sub-array // by incrementing start and decrementing end, moving inwards. reverseArrayRecursive(arr, start + 1, end - 1); } public static void main(String[] args) { // Step 1: Initialize an array int[] numbers = {10, 20, 30, 40, 50, 60}; // Step 2: Print the original array System.out.println("Original Array: " + Arrays.toString(numbers)); // Step 3: Call the recursive function to reverse the array // The initial call uses 0 as start index and length-1 as end index. reverseArrayRecursive(numbers, 0, numbers.length - 1); // Step 4: Print the reversed array System.out.println("Reversed Array: " + Arrays.toString(numbers)); // Test with an array of odd length int[] oddNumbers = {1, 2, 3, 4, 5}; System.out.println("\nOriginal Odd Length Array: " + Arrays.toString(oddNumbers)); reverseArrayRecursive(oddNumbers, 0, oddNumbers.length - 1); System.out.println("Reversed Odd Length Array: " + Arrays.toString(oddNumbers)); } }
Output
Clear
ADVERTISEMENTS