Recursive algorithm for the minimum

Hello, I tried to create a recursive algorithm for finding the minimum but it does not work, I do not understand what the problem is.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
using namespace std;

void Minimum ( int A[], int size, int &minimum){
	if(size==0) return ;
	else {
		  Minimum(A,size-1,minimum);	
		  if(minimum>A[size]){minimum=A[size];}
		  return  ;
	}
}


int main(){
	int A[]={8,65,5,10,8};
	int minimum=A[0];
	Minimum(A,5,minimum);
	cout<<"minimo : "<< minimum <<endl;
}
Last edited on
Yes, thanks for the help ...
I do not understand what the problem is.

On your first call to Minimum the size==5 and therefore on line 8 you do compare/use element A[5].

Q: Given that the A was declared: int A[]={8,65,5,10,8};, what is wrong?
A: There is no A[5]. It is out of range; one past the array.


A problem in both your and TheSmallGuy's code is that the result must have a sane value before before first call of Minimum().
In your code it specifically must equal A[0], because the recursion never checks that element. In TheSmallGuy's the result has to be initialized with something sufficiently large.
Topic archived. No new replies allowed.