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 switch0and5twice: wheni == 0and wheni == 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.