題目描述
編寫一個函數void CollectItem(const int pInput[], const int M, const int N, int pOutput[]),pInput是通過一維數組承載的M行N列的二維矩陣(使用行優先順序存放), 該函數的作用是找出該矩陣每列中的最小元素,並依次放入pOutput數組中。 void CollectItem(const int pInput[], const int M, const int N, int pOutput[]); 【輸入】 pInput: 待處理的二維矩陣,使用一維數組承載, M: 二維矩陣行數 N: 二維矩陣列數 【輸出】 pOutput: 矩陣每列的最小元素,空間已經開闢好,與二維矩陣列數等長; 【注意】只需要完成該函數功能算法,中間不需要有任何IO的輸入輸出
輸入
輸入爲二維矩陣的行數,列數,二維數組元素值。如 2,3,23,45,56,34,44,65。表示輸入的二維矩陣行數爲2,列數爲3,各元素按行優先依次爲23,45,56,34,44,65。
輸出
輸出結果爲矩陣每列中的最小元素23, 44, 56。
樣例輸入
2,3,23,45,56,34,44,65
樣例輸出
23, 44, 56
提示
1.請實現本函數,並編寫main函數完成完整輸入/輸出功能。
地區
南京研究所
public static void CollectItem(final int pInput[],final int M,final int N,int pOutput[]){
for(int i=0;i<N;i++){
int[] tempArr=new int[M];
for(int j=0;j<M;j++){//提取每列數據臨時存儲
tempArr[j]=pInput[i+j*N];
}
for(int j=0;j<M;j++){//冒泡排序(升序)
for(int k=0;k<M-j-1;k++){
if(tempArr[k]>tempArr[k+1]){
int temp=tempArr[k];
tempArr[k]=tempArr[k+1];
tempArr[k+1]=temp;
}
}
}
pOutput[i]=tempArr[0];//取最小的數據
}
for(int i=0;i<N;i++){
if(i==N-1){
System.out.print(pOutput[i]);
}else{
System.out.print(pOutput[i]+" ");
}
}
}
}
public static void main(String[] args) {
String input="2,3,23,45,56,34,44,65";
String[] inputArr=input.split(",");
int M=Integer.parseInt(inputArr[0]);
int N=Integer.parseInt(inputArr[1]);
int pInput[]=new int[M*N];
int pOutput[]=new int[N];
for(int i=0;i<N*M;i++){
pInput[i]=Integer.parseInt(inputArr[i+2]);
}
CollectItem(pInput,M,N,pOutput);
}