There is an array of 10 elements: 1234567890 . Why such a cycle:

 for (int i = 0, j = 9; i < a.length; i++) { a[i] = a[j]; j--; } 

gives out 0987667890 instead of the expected 0987654321 ?
I'm trying to rearrange the items in reverse order.

  • Because you are changing the data. That is, when you first cycle through, you already change the values ​​of a [0] instead of 1 to become equal to a [0] = 0. As one of the solutions, add another array, and write data there - Vitaly Robinovsky

1 answer 1

Because elements with indices i and j need to be swapped, and not just assign elements with index i values ​​with index j , while losing the i -th values ​​irrevocably.

You also need to go only to the middle of the array, because if you continue to the end of the array, then when you pass from a.length / 2 to a.length elements will re-exchange places, resulting in the original order.

As a result, the code looks like this:

 for (int i = 0, j = a.length - 1; i < a.length / 2; i++, j--) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } 

You can also do with just one index:

 for (int i = 0; i < a.length / 2; i++) { int tmp = a[i]; a[i] = a[a.length - i - 1]; a[a.length - i - 1] = tmp; } 

But this is someone you like more.

  • What does it mean: a [i] = a [a.length - i - 1]; a [a.length - i - 1] = tmp; exactly why a [a.length - i -1] ???? - Vitaly Ogorodnik
  • @ Vitaliy Ogorodnik a.length - i -1 is the complete analogy of index j from the first option: the initial value of a.length - 1 with a further decrease by one in each iteration - Regent