How do I reverse an int array in Java?

前端 未结 30 2393
爱一瞬间的悲伤
爱一瞬间的悲伤 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:52
    public void getDSCSort(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;
            }
        }
    
    0 讨论(0)
  • 2020-11-21 07:53

    There are already a lot of answers here, mostly focused on modifying the array in-place. But for the sake of completeness, here is another approach using Java streams to preserve the original array and create a new reversed array:

        int[] a = {8, 6, 7, 5, 3, 0, 9};
        int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length-i]).toArray();
    
    0 讨论(0)
  • 2020-11-21 07:53

    Simple for loop!

    for (int start = 0, end = array.length - 1; start <= end; start++, end--) {
        int aux = array[start];
        array[start]=array[end];
        array[end]=aux;
    }
    
    0 讨论(0)
  • 2020-11-21 07:54
    static int[] reverseArray(int[] a) {
         int ret[] = new int[a.length];
         for(int i=0, j=a.length-1; i<a.length && j>=0; i++, j--)
             ret[i] = a[j];
         return ret;
    }
    
    0 讨论(0)
  • 2020-11-21 07:55
    Collections.reverse(Arrays.asList(yourArray));
    

    java.util.Collections.reverse() can reverse java.util.Lists and java.util.Arrays.asList() returns a list that wraps the the specific array you pass to it, therefore yourArray is reversed after the invocation of Collections.reverse().

    The cost is just the creation of one List-object and no additional libraries are required.

    A similar solution has been presented in the answer of Tarik and their commentors, but I think this answer would be more concise and more easily parsable.

    0 讨论(0)
  • 2020-11-21 07:56
    public void display(){
      String x[]=new String [5];
      for(int i = 4 ; i > = 0 ; i-- ){//runs backwards
    
        //i is the nums running backwards therefore its printing from       
        //highest element to the lowest(ie the back of the array to the front) as i decrements
    
        System.out.println(x[i]);
      }
    }
    
    0 讨论(0)
提交回复
热议问题