用数据结构找出二维数组每列中最小元素,并依次放入b所指一维数组中
时间: 2023-05-27 22:03:26 浏览: 57
以下是C++代码实现:
```cpp
// 定义函数,a为二维数组,n为列数,m为行数,b为一维数组
void findMinInColumn(int a[][m], int n, int m, int b[])
{
for (int j = 0; j < n; j++) // 外层循环遍历每一列
{
int min = a[0][j]; // 假设第一个元素为该列最小值
for (int i = 1; i < m; i++) // 内层循环从第二个元素开始比较
{
if (a[i][j] < min) // 如果当前元素小于上一个最小值
{
min = a[i][j]; // 更新最小值
}
}
b[j] = min; // 将该列最小值存入b数组对应位置
}
}
```
注:此处假设二维数组的行数为m,因此需要在函数参数中与列数一同传入。
相关问题
用C语言数据结构找出二维数组每列中最小元素,并依次放入b所指一维数组中
以下是用C语言实现的代码:
```
#include <stdio.h>
void find_min(int a[][5], int* b, int rows, int cols);
int main() {
int a[3][5] = {{9, 12, 15, 7, 20}, {10, 8, 5, 14, 16}, {13, 11, 18, 6, 17}};
int b[5] = {0};
find_min(a, b, 3, 5);
printf("Minimum elements in each column:\n");
for(int i=0; i<5; i++) {
printf("%d ", b[i]);
}
printf("\n");
return 0;
}
void find_min(int a[][5], int* b, int rows, int cols) {
for(int i=0; i<cols; i++) {
int min = a[0][i];
for(int j=1; j<rows; j++) {
if(a[j][i] < min) {
min = a[j][i];
}
}
b[i] = min;
}
}
```
运行结果:
```
Minimum elements in each column:
9 8 5 6 16
```
注:本代码假设二维数组行数为3,列数为5。如果行数或列数不同,需要相应修改传入参数的值。
找出二维数组每列中最小元素,并依次放入b所指一维数组中
以下是Python实现:
```python
def get_column_min(arr):
"""
找出二维数组每列中最小元素,并依次放入b所指一维数组中
"""
m, n = len(arr), len(arr[0])
b = [float('inf')] * n
for j in range(n):
for i in range(m):
if arr[i][j] < b[j]:
b[j] = arr[i][j]
return b
```
其中,参数arr表示二维数组,返回值b表示每列的最小元素组成的一维数组。程序先用浮点数的最大值初始化b,然后遍历每列,找出其中的最小值并赋值给b。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)