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.
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 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.
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 - RegentSource: https://ru.stackoverflow.com/questions/660410/
All Articles