maneedhar
10/7/2019 - 12:38 PM

Search in a rotated sorted array

#include<bits/stdc++.h>
using namespace std;

    int search(vector<int>& v, int t) {
      int n = v.size();
      if (n == 0){
        return -1;
      }
      if (v[0]<v[n-1]){
        return bin (v, 0, n-1, t);
      }
      
      int p = pivot (v);
      if (v[0] == t)
        return 0;
      if (t < v[0])
        return bin (v, p, n-1, t);
      else
        return bin (v, 0, p-1, t);
    }
    
    int pivot (vector<int>&v){
      int n = v.size();
      int l = 0, r = n - 1;
      while (l < r){
          int m = l + (r-l)/2;
          if (v[m] > v[r])
              l = m + 1;
          else
              r = m;
      }
      return l;
  }
    
    int bin(vector<int>&v, int l, int r, int t){
      while (l <= r){
          int m = l + (r-l)/2;
          if (v[m] == t)
              return m;
          if (v[m] < t)
              l = m+1;
          else
              r = m-1;
      }
      return -1;
  }
    
int main (){
  int n;
  cin>>n;
  int t;
  cin>>t;
  vector<int>v(n);
  for (int i=0; i<n; i++){
    cin>>v[i];
  }
  cout<<search(v,t)<<endl;
  return 0;
}