+ 1

What is wrong in this code?

import java.util.Arrays; public class Main2 { public static void main(String args[]) { int[] array = {1,2,3,4,5}; System.out.println("Array = " + Arrays.toString(array)); reverse(array); System.out.println("Reversed Array = " + Arrays.toString(array)); } private static void reverse(int[] array) { int maxIndex = array.length -1; int halflength = array.length / 2; for(int i = 0; i < halflength; i++) { int temp = array[i]; array[i] = array[maxIndex-1]; array[maxIndex - i] = temp; } } } I want to reverse my array but the output is wrong.{4,4,3,2,1}

26th Jan 2019, 5:51 AM
Nitin Gutte
Nitin Gutte - avatar
2 Answers
+ 2
Just changed in line 20 -> 1 with i. https://code.sololearn.com/ctFsS1319F8e/?ref=app
26th Jan 2019, 6:05 AM
vlada
+ 2
1 and i is very similar from array[i] = array[maxIndex-1]; to array[i] = array[maxIndex-i];
26th Jan 2019, 6:06 AM
Louis
Louis - avatar