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 03:03

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?

查看更多
余生请多指教
3楼-- · 2018-12-31 03:03
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;
        }
    }
查看更多
何处买醉
4楼-- · 2018-12-31 03:05
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;
} 
查看更多
墨雨无痕
5楼-- · 2018-12-31 03:06

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.

查看更多
一个人的天荒地老
6楼-- · 2018-12-31 03:07
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;
}
查看更多
不流泪的眼
7楼-- · 2018-12-31 03:09
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]);
  }
}
查看更多
登录 后发表回答