Search element in sorted and rotated array (using binary search)

//As we know that linear search is used for sorted and unsorted both array ..


Question -
Given an rotated and sorted array, we have to search an element in this array using binary search.

Example - 
Input - arr[] = {4,5,1,2,3} , n=5, key=5
Output - Number is found at 2 position.


Input - arr[] = {4,5,1,2,3} , n=5, key=3
Output - Number is found at 5 position.

Input - arr[] = {4,5,1,2,3} , n=5, key=6
Output - Number is not found.

Approach - 

first we calculate pivot element and then divide array into 2 parts...first is 0 to pivot-1 element and second is pivot element to size-1 and first we search element in first array if element is not found then find the element in second element if element is found then index is equal to index of pivot element and the index of no found..


Implementation - 

//to find an element in sorted and rotated array

#include<iostream>

using namespace std;

int findpivot(int arr[],int n)

{

    int low=0;

    int high=n-1;

    while(low<=high){

    int mid=(low+high)/2;

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

        return mid-1;

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

        return mid;

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

        high=mid-1;

    else

    low=mid+1;

    

    }

    return 0;

}

int binarysearch(int arr[],int s,int n,int key)

{

    int low=s;

    int high=n-1;

    int mid;

    while(low<=high){

        mid=(low+high)/2;

        if(key==arr[mid])

            return mid+1;

        if(key<arr[mid])

            high=mid-1;

        if(key>arr[mid])

            low=mid+1;

        

    }

    return 0;

}

int main()

{

    int n;

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

    int key;

    cout<<"Enter the searching element : ";cin>>key;

    int arr[n];

    cout<<"Enter elemnts : "<<endl;

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

     cin>>arr[i];

    int s=findpivot(arr,n);

    s++;

    int find=binarysearch(arr,0,s,key);//return 0 if no is not found in first sorted array

    if(find==0){

         //and then call binarysearch in second sorted array

         find=binarysearch(arr,s,n,key);

         if(find!=0)

         find=find+s+1;

         if(find>=n)

         find%=n;

    }//check for position after success run of find element

    if(find)

    cout<<"Number is found at "<<find<<" position."<<endl;

    else

    cout<<"Number is not found."<<endl;

    

    return 0;

}


Time complixity - O(logn)

Comments