Given an array a and two other int variables, k and temp , write a loop that reverses the elements of the array.
for(k=0;k<a.length-1;k++){
temp=a[k];
a[k]=a[a.length-1-k];
a[a.length-1-k]=temp;
}
This is not working. Any idea why?
Given an array a and two other int variables, k and temp , write a loop that reverses the elements of the array.
for(k=0;k<a.length-1;k++){
temp=a[k];
a[k]=a[a.length-1-k];
a[a.length-1-k]=temp;
}
This is not working. Any idea why?
E.g., for a = [0, 1, 2, 3, 4, 5]
you'll switch 0
and 5
twice: when i == 0
and when i == 5
. This double-switching will put both elements into their original positions: (0, 5) -> (5, 0) -> (0, 5)
.
Try to make your loop to go through half of array only: so each pair is switched once.
You are swapping elements from each end of the array... and iterating to the items you've already swapped... is that enough of a hint?
You need to stop your loop at a.length/2 (in the middle).
for(k=0;k<a.length/2;k++)
This should work for odd and even length arrays if this is integer division.
You might also want to look at the ArrayUtils.reverse method.
Here is an example using that method.
I know you cannot use it in this assignment. But you should be aware of this and use it whenever possible, say in your assignments, projects.