How do I reverse an int array in Java?

前端 未结 30 2337
爱一瞬间的悲伤
爱一瞬间的悲伤 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:56
        public static void main(String args[])    {
            int [] arr = {10, 20, 30, 40, 50}; 
            reverse(arr, arr.length);
        }
    
        private static void reverse(int[] arr,    int length)    {
    
            for(int i=length;i>0;i--)    { 
                System.out.println(arr[i-1]); 
            }
        }
    
    0 讨论(0)
  • 2020-11-21 07:56
    private static int[] reverse(int[] array){
        int[] reversedArray = new int[array.length];
        for(int i = 0; i < array.length; i++){
            reversedArray[i] = array[array.length - i - 1];
        }
        return reversedArray;
    } 
    
    0 讨论(0)
  • 2020-11-21 07:57
    for(int i=validData.length-1; i>=0; i--){
      System.out.println(validData[i]);
     }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 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--;
        }
    }
    
    0 讨论(0)
  • 2020-11-21 08:01

    This will help you

    int a[] = {1,2,3,4,5};
    for (int k = 0; k < a.length/2; k++) {
        int temp = a[k];
        a[k] = a[a.length-(1+k)];
        a[a.length-(1+k)] = temp;
    }
    
    0 讨论(0)
提交回复
热议问题