Java Online Compiler
Example: In-Place Array Reversal with Two Pointers in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// In-Place Array Reversal with Two Pointers import java.util.Arrays; // For printing the array easily public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; System.out.println("Original Array: " + Arrays.toString(arr)); // Step 1: Initialize two pointers int start = 0; int end = arr.length - 1; // Step 2: Loop while the start pointer is less than the end pointer while (start < end) { // Step 3: Swap elements at start and end positions int temp = arr[start]; // Store the element at 'start' arr[start] = arr[end]; // Replace 'start' element with 'end' element arr[end] = temp; // Replace 'end' element with stored 'start' element // Step 4: Move pointers towards the center start++; end--; } System.out.println("Reversed Array (Two Pointers): " + Arrays.toString(arr)); } }
Output
Clear
ADVERTISEMENTS