# 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;
private:
vector<int> v;
public:
this->v = v;
}
int get(int i){
return v[i];
}
};
class Solution {
public:
int high = 1;
int low = 0;
low = high;
high <<= 1;
}
while (low <= high) {
int mid = low + (high - low) / 2;
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};
}
{-1,0,3,5,9,12}, 9
4