How do I reverse an int array in Java?

前端 未结 30 2972
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 07:18

I am trying to reverse an int array in Java.

This method does not reverse the array.

for(int i = 0; i < validData.length; i++)
{
    int temp =          


        
30条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-21 07:58

    I think it's a little bit easier to follow the logic of the algorithm if you declare explicit variables to keep track of the indices that you're swapping at each iteration of the loop.

    public static void reverse(int[] data) {
        for (int left = 0, right = data.length - 1; left < right; left++, right--) {
            // swap the values at the left and right indices
            int temp = data[left];
            data[left]  = data[right];
            data[right] = temp;
        }
    }
    

    I also think it's more readable to do this in a while loop.

    public static void reverse(int[] data) {
        int left = 0;
        int right = data.length - 1;
    
        while( left < right ) {
            // swap the values at the left and right indices
            int temp = data[left];
            data[left] = data[right];
            data[right] = temp;
    
            // move the left and right index pointers in toward the center
            left++;
            right--;
        }
    }
    

提交回复
热议问题