編寫程式碼,將矩陣的所有行按升序排序,所有列按降序排序。矩陣的大小和元素由使用者在運行時提供。
下面解釋了在C程式語言中將矩陣的所有行按升序排序,所有列按降序排序的解決方案:
用於按升序排序行的邏輯如下:
for (i=0;i<m;++i){ for (j=0;j<n;++j){ for (k=(j+1);k<n;++k){ if (ma[i][j] > ma[i][k]){ a = ma[i][j]; ma[i][j] = ma[i][k]; ma[i][k] = a; } } } }
用來依降序排序列的邏輯如下−
for (j=0;j<n;++j){ for (i=0;i<m;++i){ for (k=i+1;k<m;++k){ if (mb[i][j] < mb[k][j]){ a = mb[i][j]; mb[i][j] = mb[k][j]; mb[k][j] = a; } } } }
以下是C程式依照升序對矩陣的所有行進行排序,並按照降序對所有列進行排序 −
實時演示
##include <stdio.h> void main(){ int i,j,k,a,m,n; static int ma[10][10],mb[10][10]; printf ("Enter the order of the matrix </p><p>"); scanf ("%d %d", &m,&n); printf ("Enter co-efficients of the matrix </p><p>"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ scanf ("%d",&ma[i][j]); mb[i][j] = ma[i][j]; } } printf ("The given matrix is </p><p>"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ printf (" %d",ma[i][j]); } printf ("</p><p>"); } printf ("After arranging rows in ascending order</p><p>"); for (i=0;i<m;++i){ for (j=0;j<n;++j){ for (k=(j+1);k<n;++k){ if (ma[i][j] > ma[i][k]){ a = ma[i][j]; ma[i][j] = ma[i][k]; ma[i][k] = a; } } } } for (i=0;i<m;++i){ for (j=0;j<n;++j){ printf (" %d",ma[i][j]); } printf ("</p><p>"); } printf ("After arranging the columns in descending order </p><p>"); for (j=0;j<n;++j){ for (i=0;i<m;++i){ for (k=i+1;k<m;++k){ if (mb[i][j] < mb[k][j]){ a = mb[i][j]; mb[i][j] = mb[k][j]; mb[k][j] = a; } } } } for (i=0;i<m;++i){ for (j=0;j<n;++j){ printf (" %d",mb[i][j]); } printf ("</p><p>"); } }
當上述程式被執行時,它產生以下結果−
Enter the order of the matrix 3 4 Enter co-efficient of the matrix 1 2 3 4 1 2 3 4 5 1 2 3 The given matrix is 1 2 3 4 1 2 3 4 5 1 2 3 After arranging rows in ascending order 1 2 3 4 1 2 3 4 1 2 3 5 After arranging the columns in descending order 5 2 3 4 1 2 3 4 1 1 2 3
以上是C程式對矩陣的所有列和行進行排序的詳細內容。更多資訊請關注PHP中文網其他相關文章!