Files
javaSE-0113/day05/src/com/inmind/array01/Test07.java

50 lines
1.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.inmind.array01;
//数组的反转: 数组中的元素颠倒顺序例如原始数组为1,2,3,4,5反转后的数组为5,4,3,2,1
public class Test07 {
public static void main(String[] args) {
//方式二:不浪费空间,复杂一点,不创建新数组,在原数组的基础上进行反转
int[] arr = {1, 2, 3, 4, 5};
//对原数组进行正向遍历查看内容即可
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
System.out.println();
//定义2个索引对原数组的内容进行逐个交换到中间位置时就反转结束了
for (int start = 0, end = arr.length - 1; start < end; start++, end--) {
//定义一个变量,来进行交换操作
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
System.out.println("---------------------");
//对原数组进行正向遍历查看内容即可
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
}
public static void reverse1() {
//定义一个整数数组
int[] arr = {1, 2, 3, 4, 5};
//方式一:浪费空间,简单一点,创建新数组,进行反向遍历赋值
int[] newArr = new int[arr.length];
/*
arr1[0] = arr[arr.length - 1];
arr1[1] = arr[arr.length - 1-1];
arr1[2] = arr[arr.length - 1-2];
arr1[3] = arr[arr.length - 1-3];
*/
for (int i = arr.length - 1; i >= 0; i--) {
newArr[arr.length - 1 - i] = arr[i];
}
//对新数组正向遍历查看即可
for (int i = 0; i < newArr.length; i++) {
System.out.println(newArr[i]);
}
}
}