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.
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 arrayN/2
as for every loop, it is only necessary to know two values, the value of the current positioni
, and its counterpart from the other side. This is whatN-1-i
is doing, it starts counting from the last element of the array whilei
starts from the beginning.Basically what
a[i] = a[N-1-i]
anda[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 afterN/2
as they have already been changed.