I want to reverse the order of the int-type array, how can I do that?

Asked 2 years ago, Updated 2 years ago, 43 views

To reverse the order of int-type arrays in the method

for(int i = 0; i < validData.length; i++)
{
    int temp = validData[i];
    validData[i] = validData[validData.length - i - 1];
    validData[validData.length - i - 1] = temp;
}

I did it like this, but the order of the arrangement wasn't reversed. What went wrong?

java array

2022-09-21 17:43

1 Answers

When you flip the arrangement, hold the middle point and swap the ends.

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

You can do it like this. What's wrong with the above is that when you swap elements at both ends, you change the changed part again after the middle It's because it swaps twice and eventually returns to its original state.


2022-09-21 17:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.