Correct approach is to iterate over this array from beginning to the middle and swap elements i
and length-i-1
, i. e. first and last, second and second last and so on:
int[] arr = {1, 4, 6, 5, 23, 3, 2};
IntStream.range(0, arr.length / 2).forEach(i -> {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
});
System.out.println(Arrays.toString(arr));
// [2, 3, 23, 5, 6, 4, 1]
If you continue iterating from middle to the end, you swap them back:
IntStream.range(arr.length / 2, arr.length).forEach(i -> {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
});
System.out.println(Arrays.toString(arr));
// [1, 4, 6, 5, 23, 3, 2]
See also:
• Is there any other way to remove all whitespaces in a string?
• Is there a way to reverse specific arrays in a multidimensional array in java?