How do I reverse an int array in Java?

2018-12-31 02:19发布

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 = validData[i];
    validData[i] = validData[validData.length - i - 1];
    validData[validData.length - i - 1] = temp;
}

What is wrong with it?

30条回答
与风俱净
2楼-- · 2018-12-31 02:55

There are two ways to have a solution for the problem:

1. Reverse an array in space.

Step 1. Swap the elements at the start and the end index.

Step 2. Increment the start index decrement the end index.

Step 3. Iterate Step 1 and Step 2 till start index < end index

For this, the time complexity will be O(n) and the space complexity will be O(1)

Sample code for reversing an array in space is like:

public static int[] reverseAnArrayInSpace(int[] array) {
    int startIndex = 0;
    int endIndex = array.length - 1;
    while(startIndex < endIndex) {
        int temp = array[endIndex];
        array[endIndex] = array[startIndex];
        array[startIndex] = temp;
        startIndex++;
        endIndex--;
    }
    return array;
}

2. Reverse an array using an auxiliary array.

Step 1. Create a new array of size equal to the given array.

Step 2. Insert elements to the new array starting from the start index, from the given array starting from end index.

For this, the time complexity will be O(n) and the space complexity will be O(n)

Sample code for reversing an array with auxiliary array is like:

public static int[] reverseAnArrayWithAuxiliaryArray(int[] array) {
    int[] reversedArray = new int[array.length];
    for(int index = 0; index < array.length; index++) {
        reversedArray[index] = array[array.length - index -1]; 
    }
    return reversedArray;
}

Also, we can use the Collections API from Java to do this.

The Collections API internally uses the same reverse in space approach.

Sample code for using the Collections API is like:

public static Integer[] reverseAnArrayWithCollections(Integer[] array) {
    List<Integer> arrayList = Arrays.asList(array);
    Collections.reverse(arrayList);
    return arrayList.toArray(array);
}
查看更多
低头抚发
3楼-- · 2018-12-31 02:56

With Guava:

Collections.reverse(Ints.asList(array));
查看更多
皆成旧梦
4楼-- · 2018-12-31 02:59

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;
}
查看更多
残风、尘缘若梦
5楼-- · 2018-12-31 03:00

This is how I would personally solve it. The reason behind creating the parametrized method is to allow any array to be sorted... not just your integers.

I hope you glean something from it.

@Test
public void reverseTest(){
   Integer[] ints = { 1, 2, 3, 4 };
   Integer[] reversedInts = reverse(ints);

   assert ints[0].equals(reversedInts[3]);
   assert ints[1].equals(reversedInts[2]);
   assert ints[2].equals(reversedInts[1]);
   assert ints[3].equals(reversedInts[0]);

   reverseInPlace(reversedInts);
   assert ints[0].equals(reversedInts[0]);
}

@SuppressWarnings("unchecked")
private static <T> T[] reverse(T[] array) {
    if (array == null) {
        return (T[]) new ArrayList<T>().toArray();
    }
    List<T> copyOfArray = Arrays.asList(Arrays.copyOf(array, array.length));
    Collections.reverse(copyOfArray);
    return copyOfArray.toArray(array);
}

private static <T> T[] reverseInPlace(T[] array) {
    if(array == null) {
        // didn't want two unchecked suppressions
        return reverse(array);
    }

    Collections.reverse(Arrays.asList(array));
    return array;
}
查看更多
若你有天会懂
6楼-- · 2018-12-31 03:00

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--;
    }
}
查看更多
妖精总统
7楼-- · 2018-12-31 03:01

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();
查看更多
登录 后发表回答