jayati

Search in a Rotated Array

Sep 5th, 2023
1,141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // } Driver Code Ends
  6. class Solution{
  7.     public:
  8.     int search(int A[], int l, int h, int key){
  9.         // l: The starting index
  10.         // h: The ending index, you have to search the key in this range
  11.        
  12.         while(l<=h)
  13.         {
  14.             int mid=(l+h)/2;
  15.             if(A[mid]==key)
  16.             {
  17.                 return mid;
  18.             }
  19.             if(A[l]<=A[mid])
  20.             {
  21.                 if(key>=A[l] && key<A[mid])
  22.                 {
  23.                     h=mid-1;
  24.                 }
  25.                 else
  26.                 {
  27.                     l=mid+1;
  28.                 }
  29.             }
  30.             else
  31.             {
  32.                 if(key<=A[h] && key>A[mid])
  33.                 {
  34.                     l=mid+1;
  35.                 }
  36.                 else
  37.                 {
  38.                     h=mid-1;
  39.                 }
  40.             }
  41.         }
  42.         return -1;
  43.         //complete the function here
  44.     }
  45. };
  46.  
  47. //{ Driver Code Starts.
  48. int main() {
  49.     int t;
  50.     cin >> t;
  51.     while(t--){
  52.         int n;
  53.         cin >> n;
  54.         int A[n];
  55.         for(int i = 0; i < n; i++)
  56.             cin >> A[i];
  57.         int key;
  58.         cin >> key;
  59.         Solution ob;
  60.         cout << ob.search(A, 0, n - 1, key) << endl;
  61.     }
  62. return 0;
  63. }
  64. // } Driver Code Ends
  65. // https://practice.geeksforgeeks.org/problems/search-in-a-rotated-array4618/
Advertisement
Add Comment
Please, Sign In to add comment