Can anyone explain me please the solution of the reverseArray() method? I didn't get it :(
Anonymous #10864887
Level 22
Can anyone explain me please the solution of the reverseArray() method?
Under discussion
Comments (8)
- Popular
- New
- Old
You must be signed in to leave a comment
Hoist
9 December 2021, 05:30
Detailed examples here in codegym:
https://codegym.cc/groups/posts/reverse-an-array-in-java?fbclid=IwAR0LpZd6qKVhB2flrPndudf8isJ4V4Hyw1QX9Z7xacHNu2mgZOna-RUbwiU
0
Gellert Varga
22 November 2021, 17:36
In my opinion, the only way to discuss about a given code if it is known to both parties.
For example, I didn't download the "correct solution" to this task, I created my own solution.
It is impossible that I would have written exactly the same code as CodeGym.
So I don't know the CodeGym solution you expect me to explain.
There's also another problem: the older users who are regular visitors in the help section and often answer questions that arise: we did the OLD version of Syntax quest. Even if we click on the link to your task in your post, it does not open for us because we do not have access to the NEW Syntax you are doing.
But we are happy to respond to any published/shared concrete code or concrete questions (if we can).
+2
Anonymous #10864887
25 November 2021, 14:53
Sorry, that was my first question :) The solution given by Codegym:
public class Solution {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
printArray(array);
reverseArray(array);
printArray(array);
}
public static void reverseArray(int[] array) {
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
}
public static void printArray(int[] array) {
for (int i : array) {
System.out.print(i + ", ");
}
System.out.println();
}
}
I don't understand the line: for (int i = 0; i < array.length / 2; i++). Why array.length is divided?
+1
Thomas
26 November 2021, 12:32
That's pretty much the usual approach for the desired result. You take the first element of the array and swap it with the last element, then you take the second element and swap it with the second last and so on. That's why you just need to iterate to array.length / 2. If the array is not even then there's no need anymore to swap the middle element and so the int division is OK (that for the loop definition).
+1
Gellert Varga
27 November 2021, 23:18
Thank you Thomas! I have not been here for a few days.
0
Thomas
29 November 2021, 09:40
:) I'm not around that much either and the topic starter seems not to mind either. Hope all is well on your end?
0
Gellert Varga
29 November 2021, 21:07
Thanks, pretty much everything OK:)
0
Hoist
9 December 2021, 04:47
Appreciate the code comments to figure this out !
0