day05-数组的操作_数组遍历-数组反转方式二
This commit is contained in:
@@ -2,11 +2,36 @@ package com.inmind.array01;
|
|||||||
//数组的反转: 数组中的元素颠倒顺序,例如原始数组为1,2,3,4,5,反转后的数组为5,4,3,2,1
|
//数组的反转: 数组中的元素颠倒顺序,例如原始数组为1,2,3,4,5,反转后的数组为5,4,3,2,1
|
||||||
public class Test07 {
|
public class Test07 {
|
||||||
public static void main(String[] args) {
|
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[] arr = {1, 2, 3, 4, 5};
|
||||||
//方式一:浪费空间,简单一点,创建新数组,进行反向遍历赋值
|
//方式一:浪费空间,简单一点,创建新数组,进行反向遍历赋值
|
||||||
int[] newArr = new int[arr.length];
|
int[] newArr = new int[arr.length];
|
||||||
|
|
||||||
/*
|
/*
|
||||||
arr1[0] = arr[arr.length - 1];
|
arr1[0] = arr[arr.length - 1];
|
||||||
arr1[1] = arr[arr.length - 1-1];
|
arr1[1] = arr[arr.length - 1-1];
|
||||||
@@ -20,7 +45,5 @@ public class Test07 {
|
|||||||
for (int i = 0; i < newArr.length; i++) {
|
for (int i = 0; i < newArr.length; i++) {
|
||||||
System.out.println(newArr[i]);
|
System.out.println(newArr[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
//方式二:不浪费空间,复杂一点,不创建新数组,在原数组的基础上进行反转
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user