二维数组
数组的定义
int[][] arrays={{1,2},{2,3},{3,4},{4,5}};//二维数组的定义
数组的打印
public static void main(String[] args) {
int[][] arrays={{1,2},{2,3},{3,4},{4,5}};
for (int i = 0; i < arrays.length; i++) { //打印第一层括号内
for (int j=0;j<arrays[0].length;j++){
System.out.println(arrays[i][j]);
}
}
}
public static void PrintArrays(int[] arrays) {
for (int i = 0; i < arrays.length; i++) {
System.out.println(arrays[i]);
}
}
Arrays类运用
toString打印
import java.util.Arrays;
public class Demo05 {
public static void main(String[] args) {
int[] array={31,32,54,68,4,2,56,89};
System.out.println(Arrays.toString(array));//Arrays类打印函数toString
}
sort升序
Arrays.sort(array); //Arrays类中升序排列
冒泡排序
冒泡排序就是将数组中两个元素两两比较
import java.util.Arrays;
public class Demo05 {
public static void main(String[] args) {
int[] array={31,32,54,68,4,2,56,89};
sort(array); //调用sort方法
System.out.println(Arrays.toString(array));//Arrays类打印函数toString
}
//创造一个sort排序方法
public static int[] sort(int array[]) {
int temp = 0;
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - 1 - i; j++) {
if (array[j + 1] < array[j]) {
temp=array[j];
array[j] =array[j+1];
array[j+1]=temp;
}
}
}
return array;
}
}
稀疏数组
public class Demo06 {
public static void main(String[] args) {
//创建一个二维数组,11行11列,0没有棋子,1为黑棋,2为白棋
int[][] array=new int[11][11];
array[1][2]=1;
array[2][3]=2;
System.out.println("输出原来数组:");
for (int[] ints : array) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
//转换为稀疏数组保存
int sum=0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if(array[i][j]!=0){
sum++;
}
}
}
System.out.println("有效的数字为"+sum);
//创造一个稀疏数组
int[][] array2=new int[sum+1][3];
array2[0][0]=11;
array2[0][1]=11;
array2[0][2]=sum;
//遍历二维数组,将非0的值,放入稀疏数组中
int count=0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
if(array[i][j]!=0){
count++;
array2[count][0]=i;
array2[count][1]=j;
array2[count][2]=array[i][j];
}
}
}
//输出稀疏数组
for (int i = 0; i < array2.length; i++) {
System.out.println(array2[i][0]+"\t"
+array2[i][1]+"\t"
+array2[i][2]);
}
//将稀疏数组还原
//先读取稀疏数组
int[][] array3=new int[array2[0][0]][array2[0][1]];
//给其中数组中元素还原
for (int i = 1; i <array2.length ; i++) {
array3[array2[i][0]][array2[i][1]]=array2[i][2];
}
System.out.println("还原数组:");
for (int[] ints : array3) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
}
}