This code can only return one smallest element in a matrix, but how if I want to return smallest element in each row? I need to use recursive function in C++. Thanks for your help
#include<iostream>
using namespace std;
int smallest(int** arr, int rows, int columns, int column_index = 0)
{
if (rows <= 0 || column_index >= columns)
return INT_MAX;
if (rows == 1)
return min(*(*arr + column_index),
smallest(arr, 1, columns - 1,
column_index + 1));
return min(smallest(arr, 1, columns),
smallest(arr + 1, rows - 1, columns));
}
int main()
{
int row, col, index=0;
cin >> row;
cin >> col;
int** arr;
arr = new int* [row];
for (int i = 0; i < row; i++) {
arr[i] = new int[col];
for (int j = 0; j < col; j++) {
cin >> arr[i][j];
}
}
cout<<smallest(arr, row, col, index);
return 0;
}
I think this much code will be sufficient if you use standard algorithm - std::min_element:
If you want to do it your way (old school style, using recursion) then do something like this. You just need to fix the index of row while calling
smallest. Below is some self-explanatory code :