ronith
6/15/2018 - 10:32 AM

Find position of an element in a sorted array of infinite numbers

Suppose you have a sorted array of infinite numbers, how would you search an element in the array?

Since array is sorted, the first thing clicks into mind is binary search, but the problem here is that we don’t know size of array. If the array is infinite, that means we don’t have proper bounds to apply binary search. So in order to find position of key, first we find bounds and then apply binary search algorithm.

Let low be pointing to 1st element and high pointing to 2nd element of array, Now compare key with high index element, ->if it is greater than high index element then copy high index in low index and double the high index. ->if it is smaller, then apply binary search on high and low indices found.

// https://www.geeksforgeeks.org/find-position-element-sorted-array-infinite-numbers/
#include <iostream>
using namespace std;

int binary (int a[],int l, int r, int x){
    if (l<=r){
        int m=(l+r)/2;
        if (a[m]==x)
            return m;
        if (a[m]>x)
            return binary(a,l,m-1,x);
        return binary(a,m+1,r,x);
    }
    return -1;
}

int main(){
    int n,x;
    cin>>n;
    int a[n];
    for (int i=0;i<n;i++)
        cin>>a[i];
    cout << "Enter the search element: ";
    cin >>x;

    int l=0,r=1,k=a[0];
    while (k<x){
        l = r;
        r = 2*r;
        k = a[r];
    }
    int j=binary(a,l,r,x);
    cout<< "Index at "<<j;
}