Reputation: 31
Java Program:
int[] a = new int[] { 1, 2, 3, 4}
int N = a.length;
for (int i = 0; i < N/2; i++)
{
double temp = a[i];
a[i] = a[N-1-i];
a[N-i-1] = temp;
}
Can someone explain why the N/2 comes in the for loop? If i dry run it, initially for: i=0 , 0<2 i=1 , 1<2;
After that the for loop should stop at array {4,3,} because when i=2, the for loop is killed.
Please explain this to me.
Upvotes: 0
Views: 57
Reputation: 853
To reverse the order of an array, one can simply divide the array in half, and swap the positions of the elements that are the same distance from the middle.
For example, if you have { 1, 2, 3, 4, 5 }
, the middle would be 3, and 2 and 4 are the same distance from the middle. If you start swapping following this pattern, you would swap 2 with 4 and 1 with 5. The resulting order would { 5, 4, 3, 2 , 1 }
.
It is possible to do this with a for
loop that iterates half the length of the array N/2
as for every loop, it is only necessary to know two values, the value of the current position i
, and its counterpart from the other side. This is what N-1-i
is doing, it starts counting from the last element of the array while i
starts from the beginning.
Basically what a[i] = a[N-1-i]
and a[N-i-1] = temp
is doing is make the first element of the array equal to the last element and the last element equal to what was the original value of the first, and in the next loop the second element equals to the second last element etc... It doesn't need to keep checking the elements after N/2
as they have already been changed.
Upvotes: 1
Reputation: 5287
There is nothing wrong with the for loop in this example, it will run only twice: for i = 0
and i = 1
;
N/2 = 2
and according to question for loop executes for i = 2, this does not happen however.
Try to add print statements in the for loop and count number of print statement occurrences, you will see there are only 2. Running the code through debugger is also an option.
Final output after modification: 4, 3, 2, 1
, is this not desired result ?
Upvotes: 1