一维数组创建
-
创建
int[] arr; //声明数组引用 arr = new int[5]; //分配空间(指定长度) int[] arr2 = new int[6]; //声明与分配同时
-
初始化
//方式一 int arr1[] = new int[]{1,2,3}; //方式二 int arr2[] = {1,2,3};
-
输出
int day[] = new int[]{1,2,3,4,5,6,7}; for(int i = 0; i < 7; i ++){ System.out.println(day[i]); }
二维数组创建
-
创建
int[][] arr; arr = new int[3][4]; int[][] arr2 = new int[3][4];
-
初始化
int[][] arr = {{1,2,3}, {4,5,6}, {7,8,9}};
-
输出
int arr[][] = new int[3][4]; for(int i = 0; i < arr.length; i++){ for(int j = 0; j < a[i].length; j++){ System.out.println(arr[i][j]); } }
arr.length():返回行数
arr[i].length():返回列数
数组基本操作
-
数组遍历:
for
public static void main(String[] args) { int b[][] = new int[][]{{1}, {2,3}, {4,5,6}}; for (int i = 0; i < b.length; i++) { for (int j = 0; j < b[i].length; j++) { //每一维的列数 System.out.println(b[i][j]); } } }
-
数组排序:
Arrays.sort
public static void main(String[] args) { int[] arr = new int[]{1, 5, 2}; Arrays.sort(arr); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } }
-
数组复制:
Arrays.copyOf()
、Arrays.copyOfRange()
class ArrayDemo { public static void main(String[] args) { int[] arr = new int[]{1, 5, 2}; int[] newArr = Arrays.copyOf(arr, 5); //复制数组从0开始到末尾 for (int i = 0; i < newArr.length; i++) { System.out.println(newArr[i]); } int[] newArr2 = Arrays.copyOfRange(arr, 0, 2); //复制数组从fromIndex到toIndex for (int i = 0; i < newArr2.length; i++) { System.out.println(newArr2[i]); } } }
-
数组排序
-
冒泡排序
思想:双层循环。外层控制冒泡的次数,每次循环都将一个最大值移动到尾部;内部循环控制每一次冒泡过程
class ArrayDemo { public static void main(String[] args) { int[] arr = new int[]{1, 5, 2, 34,21}; for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { int tmp = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = tmp; } } } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
1
2
5
21
34 -
直接选择排序
思想:双层循环。外层控制选择次数;内部每次循环找出该次序列的最大值索引,后续将最大值放在该次序列最后;比较次数比冒泡排序少很多
class ArrayDemo { public static void main(String[] args) { int index; int[] arr = new int[]{1, 5, 2, 34,21}; for (int i = 0; i < arr.length - 1; i++) { index = 0; for (int j = 0; j < arr.length - i; j++) { if (arr[j] > arr[index]) { index = j; } } int tmp = arr[arr.length - i - 1]; arr[arr.length - i - 1] = arr[index]; arr[index] = tmp; } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
1
2
5
21
34
-