Find the smallest and largest number in any array(sorted or unsorted)


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

Example - 
Input - arr[] = {2,4,6,8,1,6,5,2,45,12,14} n=11
Output - 
smallest number is : 1
largest number is : 45

Approach - 
first we pick a number in smallest variable and compare this number with each number in element...same for largest

Implementation - 

//To find smallest and largest element in sorted or unsorted array

#include<iostream>

using namespace std;

int findsmallest(int arr[],int n)

{

    int smallest=arr[0];

    for(int i=0;i<n;i++){

        if(smallest>arr[i])

        smallest=arr[i];

    }

    return smallest;

}

int findlargest(int arr[],int n)

{

    int largest=arr[0];

    for(int i=0;i<n;i++){

        if(largest<arr[i])

        largest=arr[i];

    }

    return largest;

}

int main()

{

    int n;

    cout<<"Enter the no of element : ";cin>>n;

    int arr[n];

    cout<<"Enter elements : "<<endl;

    for (int i=0;i<n;i++)

        cin>>arr[i];

    int smallest=findsmallest(arr,n);

    int largest=findlargest(arr,n);

    cout<<"smallest number is : "<<smallest<<endl<<"largest number is : "<<largest<<endl;

    return 0;

}


Time complixity - O(n)

code on compiler

Comments