Finding smallest in an integer array recursively
FindSamllestRecursive() finds the smallest in an integer array recursively and returns the
smallest value. It takes 4 parameters:
arr takes the array.
i takes the index of the array.
size takes the size of the array.
smallest holds the smallest element of the
array.
Code of FindSamllestRecursive()
int FindSamllestRecursive( int arr[] , int i , int size , int smallest )
{
if ( i < size )
{
if ( arr[i] < smallest )
smallest = arr[i];
return FindSamllestRecursive( arr , i + 1 , size, smallest );
}
return smallest;
}
Summary of FindSamllestRecursive()
FindSamllestRecursive() starts from the first index of the array and
recursively calls itself until i becomes equal to or greater than the
size of array, at each function call the current element is checked against the
smallest element, if the current element at arr[i] is smaller than the
element in the smallest variable, then the current element is saved in
the smallest variable.
At each recursive function call, the current index i is incremented
by 1.
At the end, value in the smallest variable is returned from the
function.
Example
(C++)
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
int FindSamllestRecursive( int arr[] , int i , int size , int smallest )
{
if ( i < size )
{
if ( arr[i] < smallest )
smallest = arr[i];
return FindSamllestRecursive( arr , i + 1 , size, smallest );
}
return smallest;
}
int main()
{
const int size1 = 10;
int arr1[size1] = {10,20,30,40,50,60,60,70,80,90};
cout << "Smallest in array1 :
" << FindSamllestRecursive( arr1 , 1 ,
size1 , arr1[0] ); // 10
cout << endl;
const int size2 = 10;
int arr2[size2] = {85,20,30,40,50,60,60,70,75,80};
cout << "Smallest in array2 :
" << FindSamllestRecursive( arr2 , 1 ,
size2 , arr2[0] ); // 20
cout << endl;
const int size3 = 10;
int arr3[size3] = {1,2,3,4,5,6,7,8,9,0};
cout << "Smallest in array3 :
" << FindSamllestRecursive( arr3 , 1 ,
size3 , arr3[0] ); // 0
cout << endl;
const int size4 = 10;
int arr4[size4] = {10,20,30,40,50,60,70,80,90,100};
cout << "Smallest in array4 :
" << FindSamllestRecursive( arr4 , 1 ,
size4 , arr4[0] ); // 10
cout << endl;
const int size5 = 10;
int arr5[size5] = {5,10,15,20,25,30,35,40,45,50};
cout << "Smallest in array5 :
" << FindSamllestRecursive( arr5 , 1 ,
size5 , arr5[0] ); // 5
cout << endl;
_getche();
return 0;
}
Output
Smallest
in array1 : 10
Smallest
in array2 : 20
Smallest
in array3 : 0
Smallest
in array4 : 10
Smallest
in array5 : 5
0 comments:
Post a Comment