二維數組裡,有大部分空間沒使用,為了增加數組記憶體的使用效率,我們要壓縮它。
嗯,上代碼
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main(int argc, char *argv[])
5 {
6 int sparse[5][10]= {0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
7 0, 0, 0, 9, 0, 0, 0, 0, 0, 0,
8 0, 0, 0, 0, 0, 2, 0, 0, 0, 0,
9 0, 0, 0, 0, 3, 0, 0, 0, 0, 0,
10 0, 0, 0, 0, 0, 0, 0, 6, 0, 0 };//疏鬆陣列
11 int compress[6][3]; //壓縮數組
12 int i,j,k;
13 k=1;
14 compress[0][0] = 5;//數組sparse有5行
15 compress[0][1] = 10;//數組sparse 有10列
16 compress[0][2] = 5; //數組sparse有5個元素
17 for(i=0; i<5; i++) //二維數組遍曆
18 {
19 for(j=0; j<10; j++)
20 {
21 if(sparse[i][j] != 0) //元素沒被使用
22 {
23 compress[k][0] = i;//儲存行數
24 compress[k][1] = j;//儲存列數
25 compress[k][2] = sparse[i][j];//儲存元素值
26 k++;//下一行
27 }
28 }
29 }
30 for(i=0; i<6; i++) //壓縮數組輸出
31 {
32 for(j=0; j<3; j++)
33 {printf("%3d",compress[i][j]);}
34 printf("\n");
35 }
36
37
38 system("PAUSE");
39 return 0;
40 }
41