How do I reverse an int array in Java?

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

    Wouldn't doing it this way be much more unlikely for mistakes?

        int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] temp = new int[intArray.length];
        for(int i = intArray.length - 1; i > -1; i --){
                temp[intArray.length - i -1] = intArray[i];
        }
        intArray = temp;
    
    0 讨论(0)
  • 2020-11-21 07:45

    Using the XOR solution to avoid the temp variable your code should look like

    for(int i = 0; i < validData.length; i++){
        validData[i] = validData[i] ^ validData[validData.length - i - 1];
        validData[validData.length - i - 1] = validData[i] ^ validData[validData.length - i - 1];
        validData[i] = validData[i] ^ validData[validData.length - i - 1];
    }
    

    See this link for a better explanation:

    http://betterexplained.com/articles/swap-two-variables-using-xor/

    0 讨论(0)
  • 2020-11-21 07:47

    If working with data that is more primitive (i.e. char, byte, int, etc) then you can do some fun XOR operations.

    public static void reverseArray4(int[] array) {
        int len = array.length;
        for (int i = 0; i < len/2; i++) {
            array[i] = array[i] ^ array[len - i  - 1];
            array[len - i  - 1] = array[i] ^ array[len - i  - 1];
            array[i] = array[i] ^ array[len - i  - 1];
        }
    }
    
    0 讨论(0)
  • 2020-11-21 07:48

    With Commons.Lang, you could simply use

    ArrayUtils.reverse(int[] array)
    

    Most of the time, it's quicker and more bug-safe to stick with easily available libraries already unit-tested and user-tested when they take care of your problem.

    0 讨论(0)
  • 2020-11-21 07:48

    Solution with o(n) time complexity and o(1) space complexity.

    void reverse(int[] array) {
        int start = 0;
        int end = array.length - 1;
        while (start < end) {
            int temp = array[start];
            array[start] = array[end];
            array[end] = temp;
            start++;
            end--;
        }
    }
    
    0 讨论(0)
  • 2020-11-21 07:50

    In case of Java 8 we can also use IntStream to reverse the array of integers as:

    int[] sample = new int[]{1,2,3,4,5};
    int size = sample.length;
    int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1])
                          .toArray(); //Output: [5, 4, 3, 2, 1]
    
    0 讨论(0)
提交回复
热议问题