Reverse Array in Java: Explanation & Practice
Reverse an array in place
Problem summary
Write a program that reverses an array. Your code should work for ANY array.
Starter code
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5}; // Test case 1
// Reverse array in place
// Print elements space-separated
}
}Expected output and test cases
- Reverse [1,2,3,4,5]
5 4 3 2 1
- Reverse [1,2,3,4]
4 3 2 1
- Reverse [1]
1
Hints
- Swap elements from both ends
- Use two pointers: start and end
- Stop when pointers meet in middle
Related Arrays exercises
- Practice Count Even Numbers in Java
- Practice Linear Search in Java
- Practice Second Largest Element in Java
Practice all Arrays exercises · Run this idea in the Java compiler