資料結構C語言>數組>壓縮二維數組

來源:互聯網
上載者:User

二維數組裡,有大部分空間沒使用,為了增加數組記憶體的使用效率,我們要壓縮它。

嗯,上代碼

 

 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 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.