How to Reverse Array In Place

In this example, we’ll see how to reverse array in place (without creating a new array).

Input:
int[] arr1 = { 2, 5, 7, 8, 14 };
Output:
[14, 8, 7, 5, 2]

1. Java

public class ReverseArrayInPlace {

	public static void main(String[] args) {
		int arr[] = { 4, 2, 3, 1, 8, 9, 30, 12, 7 };
		System.out.println(Arrays.toString(reverseArray(arr)));
	}

	private static int[] reverseArray(int[] arr) {
		int end = arr.length - 1;
		for (int i = 0; i < arr.length; i++) {
			if (i == end || i > end) { // if mid point is countered(only one element or i exceeds the mid then break.
				break;
			}
			int temp = arr[i];
			arr[i] = arr[end];
			arr[end] = temp;
			end--;

		}
		return arr;
	}

}

Output:

[7, 12, 30, 9, 8, 1, 3, 2, 4]

Complete Java Solutions can be found here: Github Link

The complete list can be found here: Practise Programming Questions