0

Here is the code I wrote for reversing the elements in an array (Java) for example the last element becomes the first and so on. However, it doesn't quite work why is that?

public int[] reverse(int[] a) {
    int[] temp = new int[a.length];

    for (int i = 0; i < a.length - 1; i++) {
        for (int u = a.length - 1; u >= 0; u--) {
            temp[i] = a[u];
        }
    }
    return temp;
}
Plamen Nikolov
  • 2,643
  • 1
  • 13
  • 24

1 Answers1

0

The first step in debugging code is going through it as a computer would. Here you have 2 nested loops, so let's go through what happens.

We take an example array: [1, 2, 3, 4, 5].

Entering the first loop, we have i = 0, then we enter the second and set u = 4', and entering the loop we execute temp[0] = a[4]. Next we continue with the inner loop (which did not complete its condition), so we have u = 3and executetemp[0] = a[3]`. And so on...

i = 0
u = 4
temp[0] = a[4]

u = 3
temp[0] = a[3]

u = 2
temp[0] = a[2]
...
u = 0
temp[0] = a[0] 

i = 1
u = 4 
temp[1] = a[4]

u = 3 
temp[1] = a[3]

u = 2
temp[1] = a[2]
...

u = 0
temp[1] = a[0]
...

So you finish up by adding the first element of the array in your resulting array.

damianr13
  • 440
  • 3
  • 9