如何在Java中反转int数组?

时间:2021-05-26 07:42:25

I am trying to reverse an int array in Java.

我正在尝试在Java中反转一个int数组。

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?

这有什么问题吗?

35 个解决方案

#1


224  

To reverse an int array, you swap items up until you reach the midpoint, like this:

要反转一个int数组,您可以将项目交换到中点,如下所示:

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

The way you are doing it, you swap each element twice, so the result is the same as the initial list.

这样做的方式是,将每个元素交换两次,因此结果与初始列表相同。

#2


265  

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.

大多数情况下,当他们处理好你的问题时,你可以更快速、更安全地使用现成的库,而这些库已经经过了测试和用户测试。

#3


42  

public class ArrayHandle {
    public static Object[] reverse(Object[] arr) {
        List<Object> list = Arrays.asList(arr);
        Collections.reverse(list);
        return list.toArray();
    }
}

#4


35  

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.

我还认为在while循环中这样做更容易理解。

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--;
    }
}

#5


23  

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().

能扭转java.util java.util.Collections.reverse()。列表和java.util.Arrays.asList()返回一个包含您传递给它的特定数组的列表,因此在调用了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.

在塔里克的回答和他们的评论中也提出了类似的解决方案,但我认为这个答案应该更简洁,更容易被解析。

#6


6  

With Guava:

番石榴:

Collections.reverse(Ints.asList(array));

#7


5  

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;
}

#8


5  

Simple for loop!

简单的for循环!

for (int start = 0, end = array.length - 1; start <= end; start++, end--) {
    int aux = array[start];
    array[start]=array[end];
    array[end]=aux;
}

#9


5  

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:

这里已经有了很多的答案,主要集中在对数组的就地修改。但是为了完整性起见,这里是另一种使用Java流来保存原始数组并创建新的反向数组的方法:

    int[] a = {8, 6, 7, 5, 3, 0, 9};
    int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length-i]).toArray();

#10


4  

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

如果处理的数据更原始(比如char、byte、int等),那么您可以进行一些有趣的XOR操作。

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];
    }
}

#11


4  

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);
    assertEquals(Integer.valueOf(1), reversedInts[3]);
    assertEquals(Integer.valueOf(4), reversedInts[0]);
}

public static <T> T[] reverse(T[] arrayToReverse){
   //as per the collections spec (and pointed out by @Radiodef)
   // the collections api will sort the array in place.
   Collections.reverse(Arrays.asList(arrayToReverse));
   return arrayToReverse;
}

#12


4  

for(int i=validData.length-1; i>=0; i--){
  System.out.println(validData[i]);
 }

#13


3  

It is most efficient to simply iterate the array backwards.

简单地向后迭代数组是最有效的。

I'm not sure if Aaron's solution does this vi this call Collections.reverse(list); Does anyone know?

我不确定Aaron的解决方案是否会把这个叫做Collections.reverse(list);有人知道吗?

#14


2  

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

你的程序只对长度= 0,1。你可以尝试:

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

#15


2  

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]);
  }
}

#16


2  

Here's a simple an quick solution. Hope it helps!.

这里有一个简单的快速解决方案。希望它能帮助!

public int[] reverse(int[] arr) {
    for(int i = arr.length; i > 0 ; i--){
        System.out.print(arr[i-1] + " ");
    }
    return arr;
}

#17


2  

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;
        }
    }

#18


1  

In case of Java 8 we can also use streams to reverse the integer array as:

在Java 8的情况下,我们也可以使用流来将整数数组反转为:

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]

#19


0  

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;

#20


0  

below is the complete program to run in your machine.

下面是在您的机器中运行的完整程序。

public class ReverseArray {
    public static void main(String[] args) {
        int arr[] = new int[] { 10,20,30,50,70 };
        System.out.println("reversing an array:");
        for(int i = 0; i < arr.length / 2; i++){
            int temp = arr[i];
            arr[i] = arr[arr.length - i - 1];
            arr[arr.length - i - 1] = temp;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }   
    }
}

For programs on matrix using arrays this will be the good source.Go through the link.

对于矩阵使用数组的程序,这将是一个好的来源。通过链接。

#21


0  

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

使用XOR解决方案来避免temp变量,您的代码应该是这样的。

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/

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

#22


0  

public class TryReverse {
    public static void main(String[] args) {        
        int [] array = {2,3,4,5,6,7,8,9};       
        reverse(array);
        for(int i=0; i<array.length; ++i)
            System.out.print(array[i] + " ");
    }
    public static void reverse (int [] array){
        for(int start=0, end=array.length-1; start<=end; start++, end--){
            int aux = array[start];
            array[start]=array[end];
            array[end]=aux;
        }
    }
}

#23


0  

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;
} 

#24


0  

Try this code:

试试这段代码:

    int arr[] = new int[]{1,2,3,4,5,6,7};
    for(int i=0;i<arr.length/2;i++){
        int temp = arr[i];
        arr[i] = arr[(arr.length-1)-i];
        arr[(arr.length-1)-i] = temp;
     }
     System.out.println(Arrays.toString(arr));

#25


0  

Here is a simple implementation, to reverse array of any type, plus full/partial support.

这里有一个简单的实现,可以反转任意类型的数组,加上完全/部分支持。

import java.util.logging.Logger;

public final class ArrayReverser {
 private static final Logger LOGGER = Logger.getLogger(ArrayReverser.class.getName());

 private ArrayReverser () {

 }

 public static <T> void reverse(T[] seed) {
    reverse(seed, 0, seed.length);
 }

 public static <T> void reverse(T[] seed, int startIndexInclusive, int endIndexExclusive) {
    if (seed == null || seed.length == 0) {
        LOGGER.warning("Nothing to rotate");
    }
    int start = startIndexInclusive < 0 ? 0 : startIndexInclusive;
    int end = Math.min(seed.length, endIndexExclusive) - 1;
    while (start < end) {
        swap(seed, start, end);
        start++;
        end--;
    }
}

 private static <T> void swap(T[] seed, int start, int end) {
    T temp =  seed[start];
    seed[start] = seed[end];
    seed[end] = temp;
 }  

}

Here is the corresponding Unit Test

这是相应的单元测试。

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Before;
import org.junit.Test;

public class ArrayReverserTest {
private Integer[] seed;

@Before
public void doBeforeEachTestCase() {
    this.seed = new Integer[]{1,2,3,4,5,6,7,8};
}

@Test
public void wholeArrayReverse() {
    ArrayReverser.<Integer>reverse(seed);
    assertThat(seed[0], is(8));
}

 @Test
 public void partialArrayReverse() {
    ArrayReverser.<Integer>reverse(seed, 1, 5);
    assertThat(seed[1], is(5));
 }
}

#26


0  

Another way to reverse array

另一种反向排列的方法。

public static int []reversing(int[] array){
    int arraysize = array.length;
    int[] reverse = new int [arraysize+1];
    for(int i=1; i <= arraysize ; i++){
        int dec= arraysize -i;
        reverse[i] = array[dec];
    }
    return reverse;
}

#27


0  

This works if you want to reverse until you get to the middle of the array?

如果你想要翻转到数组的中间,这是可行的吗?

    double [] list = {11,21,31,41,51,61,71,81,91};
    int midpoint = list.length/2 -1;
    int firstVal = 0;
    while(firstVal < midpoint){
        double midPoint = list[midpoint];
        double firstValue = list[firstVal];
        list[midpoint] = firstValue;
        list[firstVal] = midPoint;

        firstVal = firstVal + 1;
        midpoint = midpoint-1;
    }
    StdOut.println(Arrays.toString(list));
}

#28


0  

As I intended to keep my original Array as it was, I solved this problem in the following manner:

当我打算保持原来的数组时,我用如下方式解决了这个问题:

List<Integer> normalArray= new ArrayList<>();
List<Integer> reversedArray = new ArrayList<>();

// Fill up array here

for (int i = 1; i <= normalArray.size(); i++) {
  reversedArray .add(normalArray.get(normalArray.size()-i));
}

So basically loop through the initial array and add all the values in reversed order to the new (reversed) array. The type of the list can be anything. I work my way through this code multiple times, this causes some of the other solutions not to work.

因此,基本上循环遍历初始数组并将所有的值添加到新(反向)数组中。列表的类型可以是任何东西。我多次使用这个代码,这导致一些其他的解决方案不工作。

#29


0  

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

具有o(n)时间复杂度和o(1)空间复杂度的解决方案。

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--;
    }
}

#30


0  

Here is what I've come up with:

以下是我的想法:

// solution 1 - boiler plated 
Integer[] original = {100, 200, 300, 400};
Integer[] reverse = new Integer[original.length];

int lastIdx = original.length -1;
int startIdx = 0;

for (int endIdx = lastIdx; endIdx >= 0; endIdx--, startIdx++)
   reverse[startIdx] = original[endIdx];

System.out.printf("reverse form: %s", Arrays.toString(reverse));

// solution 2 - abstracted 
// convert to list then use Collections static reverse()
List<Integer> l = Arrays.asList(original);
Collections.reverse(l);
System.out.printf("reverse form: %s", l);

#1


224  

To reverse an int array, you swap items up until you reach the midpoint, like this:

要反转一个int数组,您可以将项目交换到中点,如下所示:

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

The way you are doing it, you swap each element twice, so the result is the same as the initial list.

这样做的方式是,将每个元素交换两次,因此结果与初始列表相同。

#2


265  

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.

大多数情况下,当他们处理好你的问题时,你可以更快速、更安全地使用现成的库,而这些库已经经过了测试和用户测试。

#3


42  

public class ArrayHandle {
    public static Object[] reverse(Object[] arr) {
        List<Object> list = Arrays.asList(arr);
        Collections.reverse(list);
        return list.toArray();
    }
}

#4


35  

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.

我还认为在while循环中这样做更容易理解。

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--;
    }
}

#5


23  

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().

能扭转java.util java.util.Collections.reverse()。列表和java.util.Arrays.asList()返回一个包含您传递给它的特定数组的列表,因此在调用了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.

在塔里克的回答和他们的评论中也提出了类似的解决方案,但我认为这个答案应该更简洁,更容易被解析。

#6


6  

With Guava:

番石榴:

Collections.reverse(Ints.asList(array));

#7


5  

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;
}

#8


5  

Simple for loop!

简单的for循环!

for (int start = 0, end = array.length - 1; start <= end; start++, end--) {
    int aux = array[start];
    array[start]=array[end];
    array[end]=aux;
}

#9


5  

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:

这里已经有了很多的答案,主要集中在对数组的就地修改。但是为了完整性起见,这里是另一种使用Java流来保存原始数组并创建新的反向数组的方法:

    int[] a = {8, 6, 7, 5, 3, 0, 9};
    int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length-i]).toArray();

#10


4  

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

如果处理的数据更原始(比如char、byte、int等),那么您可以进行一些有趣的XOR操作。

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];
    }
}

#11


4  

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);
    assertEquals(Integer.valueOf(1), reversedInts[3]);
    assertEquals(Integer.valueOf(4), reversedInts[0]);
}

public static <T> T[] reverse(T[] arrayToReverse){
   //as per the collections spec (and pointed out by @Radiodef)
   // the collections api will sort the array in place.
   Collections.reverse(Arrays.asList(arrayToReverse));
   return arrayToReverse;
}

#12


4  

for(int i=validData.length-1; i>=0; i--){
  System.out.println(validData[i]);
 }

#13


3  

It is most efficient to simply iterate the array backwards.

简单地向后迭代数组是最有效的。

I'm not sure if Aaron's solution does this vi this call Collections.reverse(list); Does anyone know?

我不确定Aaron的解决方案是否会把这个叫做Collections.reverse(list);有人知道吗?

#14


2  

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

你的程序只对长度= 0,1。你可以尝试:

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

#15


2  

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]);
  }
}

#16


2  

Here's a simple an quick solution. Hope it helps!.

这里有一个简单的快速解决方案。希望它能帮助!

public int[] reverse(int[] arr) {
    for(int i = arr.length; i > 0 ; i--){
        System.out.print(arr[i-1] + " ");
    }
    return arr;
}

#17


2  

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;
        }
    }

#18


1  

In case of Java 8 we can also use streams to reverse the integer array as:

在Java 8的情况下,我们也可以使用流来将整数数组反转为:

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]

#19


0  

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;

#20


0  

below is the complete program to run in your machine.

下面是在您的机器中运行的完整程序。

public class ReverseArray {
    public static void main(String[] args) {
        int arr[] = new int[] { 10,20,30,50,70 };
        System.out.println("reversing an array:");
        for(int i = 0; i < arr.length / 2; i++){
            int temp = arr[i];
            arr[i] = arr[arr.length - i - 1];
            arr[arr.length - i - 1] = temp;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }   
    }
}

For programs on matrix using arrays this will be the good source.Go through the link.

对于矩阵使用数组的程序,这将是一个好的来源。通过链接。

#21


0  

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

使用XOR解决方案来避免temp变量,您的代码应该是这样的。

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/

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

#22


0  

public class TryReverse {
    public static void main(String[] args) {        
        int [] array = {2,3,4,5,6,7,8,9};       
        reverse(array);
        for(int i=0; i<array.length; ++i)
            System.out.print(array[i] + " ");
    }
    public static void reverse (int [] array){
        for(int start=0, end=array.length-1; start<=end; start++, end--){
            int aux = array[start];
            array[start]=array[end];
            array[end]=aux;
        }
    }
}

#23


0  

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;
} 

#24


0  

Try this code:

试试这段代码:

    int arr[] = new int[]{1,2,3,4,5,6,7};
    for(int i=0;i<arr.length/2;i++){
        int temp = arr[i];
        arr[i] = arr[(arr.length-1)-i];
        arr[(arr.length-1)-i] = temp;
     }
     System.out.println(Arrays.toString(arr));

#25


0  

Here is a simple implementation, to reverse array of any type, plus full/partial support.

这里有一个简单的实现,可以反转任意类型的数组,加上完全/部分支持。

import java.util.logging.Logger;

public final class ArrayReverser {
 private static final Logger LOGGER = Logger.getLogger(ArrayReverser.class.getName());

 private ArrayReverser () {

 }

 public static <T> void reverse(T[] seed) {
    reverse(seed, 0, seed.length);
 }

 public static <T> void reverse(T[] seed, int startIndexInclusive, int endIndexExclusive) {
    if (seed == null || seed.length == 0) {
        LOGGER.warning("Nothing to rotate");
    }
    int start = startIndexInclusive < 0 ? 0 : startIndexInclusive;
    int end = Math.min(seed.length, endIndexExclusive) - 1;
    while (start < end) {
        swap(seed, start, end);
        start++;
        end--;
    }
}

 private static <T> void swap(T[] seed, int start, int end) {
    T temp =  seed[start];
    seed[start] = seed[end];
    seed[end] = temp;
 }  

}

Here is the corresponding Unit Test

这是相应的单元测试。

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Before;
import org.junit.Test;

public class ArrayReverserTest {
private Integer[] seed;

@Before
public void doBeforeEachTestCase() {
    this.seed = new Integer[]{1,2,3,4,5,6,7,8};
}

@Test
public void wholeArrayReverse() {
    ArrayReverser.<Integer>reverse(seed);
    assertThat(seed[0], is(8));
}

 @Test
 public void partialArrayReverse() {
    ArrayReverser.<Integer>reverse(seed, 1, 5);
    assertThat(seed[1], is(5));
 }
}

#26


0  

Another way to reverse array

另一种反向排列的方法。

public static int []reversing(int[] array){
    int arraysize = array.length;
    int[] reverse = new int [arraysize+1];
    for(int i=1; i <= arraysize ; i++){
        int dec= arraysize -i;
        reverse[i] = array[dec];
    }
    return reverse;
}

#27


0  

This works if you want to reverse until you get to the middle of the array?

如果你想要翻转到数组的中间,这是可行的吗?

    double [] list = {11,21,31,41,51,61,71,81,91};
    int midpoint = list.length/2 -1;
    int firstVal = 0;
    while(firstVal < midpoint){
        double midPoint = list[midpoint];
        double firstValue = list[firstVal];
        list[midpoint] = firstValue;
        list[firstVal] = midPoint;

        firstVal = firstVal + 1;
        midpoint = midpoint-1;
    }
    StdOut.println(Arrays.toString(list));
}

#28


0  

As I intended to keep my original Array as it was, I solved this problem in the following manner:

当我打算保持原来的数组时,我用如下方式解决了这个问题:

List<Integer> normalArray= new ArrayList<>();
List<Integer> reversedArray = new ArrayList<>();

// Fill up array here

for (int i = 1; i <= normalArray.size(); i++) {
  reversedArray .add(normalArray.get(normalArray.size()-i));
}

So basically loop through the initial array and add all the values in reversed order to the new (reversed) array. The type of the list can be anything. I work my way through this code multiple times, this causes some of the other solutions not to work.

因此,基本上循环遍历初始数组并将所有的值添加到新(反向)数组中。列表的类型可以是任何东西。我多次使用这个代码,这导致一些其他的解决方案不工作。

#29


0  

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

具有o(n)时间复杂度和o(1)空间复杂度的解决方案。

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--;
    }
}

#30


0  

Here is what I've come up with:

以下是我的想法:

// solution 1 - boiler plated 
Integer[] original = {100, 200, 300, 400};
Integer[] reverse = new Integer[original.length];

int lastIdx = original.length -1;
int startIdx = 0;

for (int endIdx = lastIdx; endIdx >= 0; endIdx--, startIdx++)
   reverse[startIdx] = original[endIdx];

System.out.printf("reverse form: %s", Arrays.toString(reverse));

// solution 2 - abstracted 
// convert to list then use Collections static reverse()
List<Integer> l = Arrays.asList(original);
Collections.reverse(l);
System.out.printf("reverse form: %s", l);