How do I reverse an int array in Java?

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

    Your program will work for only length = 0, 1. You can try :

    int i = 0, j = validData.length-1 ; 
    while(i < j)
    {
         swap(validData, i++, j--);  // code for swap not shown, but easy enough
    }
    

提交回复
热议问题