RSS

A sorted array is rotated any number of time. How will you do binary search on that

Fri, Mar 5, 2010

Algorithm

The logic is
1.) Divide the array into two halves.
2.) 1 will be sorted one.
3.) while the other one would be again circularly sorted.
4.) check for element in sorted one.
note: the array being the sorted one can b verified if v make the following comparison
a[first element ] 5.) if the element v are looking for is not in the sorted array .
6.) again go for partitioning of the circularly sorted array .
7.) this way I guess we would get the required element.

 
#include
#include
using namespace std;
int search(int v[], int low, int high, int key)
{
         if(low>high)
           return -1;
         int mid=int(floor(float((float(low)+float(high))/2)));
         if(v[mid]==key)
           return v[mid];
         if(v[low]>v[high])
         {
           if(v[mid]>v[high])
           {
             if(v[mid]                return search(v,mid+1,high,key);
             else  if(v[mid]>key&&v[low]<=key)
               return search(v,low,mid-1,key);
             else
               return search(v,mid+1,high,key);
           }
           else
           {
             if(v[mid]=key)
               return  search(v,mid+1,high,key);
             else
               return search(v,low,mid-1,key);
           }
         }
         else
         {
           if(key                return search(v,low,mid-1,key);
           else
               return search(v,mid+1,high,key);
         }
}
  
 
int main()
{
         int n;
         cout<<”\nEnter the number of elements=”;
         cin>>n;
         int array[n];
         cout<<”\nEnter the elements:”;
         for(int i=0;i            cin>>array[i];
         int k;
         cout<<”\nEnter the number to search=”;
         cin>>k;
         int found=0;
         if(search(array, 0, n-1, k)!=-1)
            found=1;
 
         if(found==1)
            cout<<”\nNumber is found”;
         else
           cout<<”\nNumber is not found”;
         return 0;
}
 
Complexity =O(log n)

Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Other Posts:

This post was written by:

eXclusiveMinds - who has written 500 posts on eXclusiveMinds.


Contact the author

Leave a Reply

You must be logged in to post a comment.