Requirement:
编写一程序,把M×N矩阵a的元素逐列按降序排列。假设M、N不超过10。分别编写求一维数组元素值最大和元素值最小的函数,主函数中初始化一个二维数组a[10][10],调用定义的两函数输出每行、每列的最大值
代码:
// MatrixSort.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream.h> void bubble_sort(int a[],int n) { int temp=0; for( int i=0;i<n;i++ ) for(int j=n-1;j>i;j--) { if(a[i]<a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } void bubble_sort2(int** a,int n) { int temp=0; for( int i=0;i ) for(int j=n-1;j>i;j--) { if(**(a+i)<**(a+j)) { temp=**(a+i); **(a+i)=**(a+j); **(a+j)=temp; } } } void formatMatrix(int* matrix, int linesize , int columnsize) { for(int j=0 ; j<columnsize ; j++) { int** col = new int*[linesize] ; for(int i=0 ; i<linesize ; i++ ) *(col+i) = matrix+i*columnsize+j; bubble_sort2(col ,linesize ) ; delete[] col ; } } void showMaxAndMin(int* matrix, int linesize , int columnsize) { int* max = new int[columnsize] ; int* min = new int[columnsize] ; for (int i=0; i<columnsize; i++) { max[i] = *(matrix+i) ; min[i] = *(matrix+(linesize-1)*columnsize+i) ; } cout<<endl ; cout<<"Min value: " ; for (int j=0; j<columnsize; j++) { cout<<min[j]<<" " ; } cout<<endl ; cout<<"Max value: " ; for (int k=0; k<columnsize; k++) { cout<<max[k]<<" " ; } cout<<endl<<endl ; delete[] max ; delete[] min ; } int main(int argc, char* argv[]) { int a[5][5] = { {1,3,8,2,4}, {5,2,8,9,3}, {4,1,6,0,7}, {3,0,1,2,5}, {8,3,0,8,4}, } ; // Calculate linesize and columnsize of matrix int columnsize = sizeof(a[0])/sizeof(int) ; int linesize = sizeof(a)/sizeof(int)/columnsize ; cout<<"Column Size="< < Line Size= "< < " ; } cout<< endl ; } // Print min and max values for each column showMaxAndMin(* a, linesize, columnsize) ; return 0; }