How do I reverse an int array in Java?

前端 未结 30 2355
爱一瞬间的悲伤
爱一瞬间的悲伤 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 08:01

     public static int[] reverse(int[] array) {
    
        int j = array.length-1;
        // swap the values at the left and right indices //////
            for(int i=0; i<=j; i++)
            {
                 int temp = array[i];
                    array[i] = array[j];
                    array[j] = temp;
               j--;
            }
    
             return array;
        }
    
          public static void main(String []args){
            int[] data = {1,2,3,4,5,6,7,8,9};
            reverse(data);
    
        }
    

提交回复
热议问题