write a function that sorts the smallest element in the array

Write a recursive function that finds and returns the minimum or smallest elemnt in an array, where the array and its size are given as parameters.

Solution:

#include <iostream>
using namespace std;

int smallest_element(int [], int size);

int main()
{
int array[5] = {9,-8,1,8,-7};
cout << “Smallest element of array is ” << smallest_element(array,5) << endl;
return 0;
}

//Function
int smallest_element(int array[], int counter)
{
int smallest;
if (counter == 1)
return array[0];
else
{
smallest = smallest_element(array+1,counter-1);
if (smallest < array[0])
return smallest;
else
return array[0];
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s