Find the smallest and largest number in sorted and rotated array

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

Example -
Input : arr[] = {10,2,4,6,8,9}  , n=6
Output - 
smallest number is : 2
largest number  is : 10

Approach - 
first we find the pivot element which is largest element in sorted and rotated array and next element is the smallest element in sorted and rotated array.

Implementation -

//find the smallest and largest element in sorted and rotated array

#include<iostream>

using namespace std;

int findpivot(int arr[],int n)

{

    int low=0;

    int high=n-1;

    int mid;

    while(low<=high){

        if(mid<high&&arr[mid]>arr[mid+1])

        return mid;

        if(mid>low&&arr[mid]<arr[mid-1])

        return mid-1;

        if(arr[low]>arr[mid])

        high=mid-1;

        else

        low=mid+1;

    }

}

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 pivot=findpivot(arr,n);

    cout<<"smallest number is : "<<arr[pivot+1]<<endl<<"largest number is : "<<arr[pivot]<<endl;

    return 0;

}

Note - this logic is only applicable on sorted and rotated array, not applicable at sorted array.

Time complixity - O(logn)

Code on compiler





















Comments