Find the smallest and largest number in any sorted arary

Question - 
To find the smallest and largest number in any sorted array.

Example
Input - arr[] = {1,2,3,4,5} , n=5
Output - 
smallest number is : 1
largest number is : 5

Input - arr[] = {2,6,7,10,15,25,30} n=7
Output - 
smallest number is : 2
largest number is : 30

Approach - 
In a sorted array smallest element is at first position and largest element is at last position.

Implementation - 

//To find the maximum and minimum element in sorted array
#include<iostream>
using namespace std;
int findlargest(int arr[],int n)
{
    return arr[n-1];
}
int findsmallest(int arr[],int n)
{
    return arr[0];
}
int main()
{
    int n;
    cout<<"Enter the no of elements : ";cin>>n;
    int arr[n];
    cout<<"Enter elements : "<<endl;
    for(int i=0;i<n;i++)
        cin>>arr[i];
    
    int largest=findlargest(arr,n);
    int smallest=findsmallest(arr,n);
    cout<<"smallest number is : "<<smallest<<endl;
    cout<<"Largest number is : "<<largest<<endl;
}


Time Complixity - O(1)

Comments