Search in a Sorted Array of Unknown Size in C++

C++Server Side ProgrammingProgramming

Suppose we have an array and that is sorted in ascending order, we have to define a function to search target in nums. If the target is present, then return its index, otherwise, return -1.

The array size is not known. We can only access the array using an ArrayReader interface. There is a get function like ArrayReader.get(k) this will return the element of the array at index k.

So, if the input is like array = [-1,0,3,5,9,12], target = 9, then the output will be 4 as 9 exists in nums and its index is 4

To solve this, we will follow these steps −

  • high := 1, low := 0

  • while get(high) of reader < target, do −

    • low := high

    • high = high * 2

  • while low <= high, do −

    • mid := low + (high - low) / 2

    • x := get(mid) of reader

    • if x is same as target, then −

      • return mid

    • if x > target, then −

      • high := mid - 1

    • Otherwise

      • low := mid + 1

  • return -1

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class ArrayReader{
private:
   vector<int> v;
public:
   ArrayReader(vector<int> &v){
      this->v = v;
   }
   int get(int i){
      return v[i];
   }
};
class Solution {
public:
   int search(ArrayReader& reader, int target) {
      int high = 1;
      int low = 0;
      while (reader.get(high) < target) {
         low = high;
         high <<= 1;
      }
      while (low <= high) {
         int mid = low + (high - low) / 2;
         int x = reader.get(mid);
         if (x == target)
            return mid;
         if (x > target) {
            high = mid - 1;
         }
         else
            low = mid + 1;
      }
      return -1;
   }
};
main(){
   Solution ob;
   vector<int> v = {-1,0,3,5,9,12};
   ArrayReader reader(v);
   cout<<(ob.search(reader, 9));
}

Input

{-1,0,3,5,9,12}, 9

Output

4
raja
Published on 17-Nov-2020 10:36:23
Advertisements