JAVA数组元素反转的三种写法------JAVA入门基础教程

int[] arr = new int[]{34,54,3,2,65,7,34,5,76,34,67};
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;
}

for(int i = 0;i < arr.length;i++)
{
    System.out.print(arr[i] + "\t");
}
System.out.println();
//互换方法2
int[] newArr = new int[arr.length];
for(int i = arr.length - 1;i >= 0;i--)
{
    newArr[arr.length - 1 - i] = arr[i];
    System.out.print(arr[i]+"\t");
}
System.out.println();
//互换方法3
for(int i = 0,j = arr.length - 1;i < j;i++,j--)
{
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    System.out.print(arr[i]+"\t");
}

你可能感兴趣的:(JAVA随手写,java,算法,排序算法,数据结构,intellij-idea)