稀疏数组可以看做是普通数组的压缩,但是这里说的普通数组是值无效数据量远大于有效数据量的数组
形如:
0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 2 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
其稀疏数组形式:
11 11 2
1 2 1
2 4 2
2.存储
刚说到稀疏数组是一种压缩后的数组,为什么要进行压缩存储呢?
原数组中存在大量的无效数据,占据了大量的存储空间,真正有用的数据却少之又少
压缩存储可以节省存储空间以避免资源的不必要的浪费,在数据序列化到磁盘时,压缩存储可以提高IO效率
package Structure;
import org.w3c.dom.ls.LSOutput;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.StandardSocketOptions;
public class SparseArray {
public static void main(String[] args) throws IOException {
//创建一个原始的二维数组11*11
//0表示没有棋子,1表示黑子,2表示蓝子
int chessArr[][] = new int[11][11];
chessArr[1][2] = 1;
chessArr[2][3] = 2;
chessArr[4][5] = 2;
//输出原始的二维数组
System.out.println("输出原始的二维数组:");
for (int[] row : chessArr)
for (int data : row)
System.out.printf("%d\t", data);
System.out.println();
//将二维数组转化为稀疏数组
//先遍历二维数组,得到非0数据的个数
int sum = 0;
for (int i = 0; i < 11; i++)
for (int j = 0; j < 11; j++)
if (chessArr[i][j] != 0)
sum++;
//创建对应的稀疏数组
int sparseArray[][] = new int[sum + 1][3];
//给稀疏数组赋值
sparseArray[0][0] = 11;
sparseArray[0][1] = 11;
sparseArray[0][2] = sum;
//遍历二维数组,将非0值存放到稀疏数组中
int count = 0;//用于记录这是第几个非0数据
for (int i = 0; i < 11; i++)
for (int j = 0; j < 11; j++) {
if (chessArr[i][j] != 0) {
count++;
sparseArray[count][0] = i;
sparseArray[count][1] = j;
sparseArray[count][2] = chessArr[i][j];
}
}
//输出稀疏数组的形式
System.out.println();
System.out.println("得到的稀疏数组形式如下:");
for (int i = 0; i < sparseArray.length; i++) {
System.out.printf("%d\t%d\t%d\t\n", sparseArray[i][0], sparseArray[i][1], sparseArray[i][2]);
}
//将二维数组写入文件,每行数据之间TAB间隔
File file = new File("f://array.txt");//存放数组数据的文件
FileWriter out = new FileWriter(file);//文件写入流
for (int i = 0; i < sparseArray.length; i++) {
out.write(sparseArray[i][0] + "\t");
out.write(sparseArray[i][1] + "\t");
out.write(sparseArray[i][2] + "\t");
out.write("\n");
}
out.close();
//从文件中读取二维数组
//将稀疏数组还原成原始二维数组
//先读取稀疏数组的第一行,创建新的二维数组
int chessArr2[][] = new int[sparseArray[0][0]][sparseArray[0][1]];
//将稀疏数组的非零项归还给二维数组
for (int i = 1; i < sparseArray.length; i++)
chessArr2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
//输出恢复后的二维数组
System.out.println();
System.out.println("恢复后的二维数组:");
for(int row[]:chessArr2)
for(int data:row)
System.out.printf("%d\t",data);
System.out.println();
}
}
https://blog.csdn.net/weixin_41922289/article/details/94555391