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

17 Aug, 2021
Suppose you have a sorted array of infinite numbers, how would you search an element in the array?Source: Amazon Interview Experience. 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.  
Below are implementations of above algorithm 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to demonstrate working of an algorithm that finds// an element in an array of infinite size#include<bits/stdc++.h>using namespace std; // Simple binary search algorithmint binarySearch(int arr[], int l, int r, int x){    if (r>=l)    {        int mid = l + (r - l)/2;        if (arr[mid] == x)            return mid;        if (arr[mid] > x)            return binarySearch(arr, l, mid-1, x);        return binarySearch(arr, mid+1, r, x);    }    return -1;} // function takes an infinite size array and a key to be//  searched and returns its position if found else -1.// We don't know size of arr[] and we can assume size to be// infinite in this function.// NOTE THAT THIS FUNCTION ASSUMES arr[] TO BE OF INFINITE SIZE// THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKINGint findPos(int arr[], int key){    int l = 0, h = 1;    int val = arr[0];     // Find h to do binary search    while (val < key)    {        l = h;        // store previous high        h = 2*h;      // double high index        val = arr[h]; // update new val    }     // at this point we have updated low and    // high indices, Thus use binary search    // between them    return binarySearch(arr, l, h, key);} // Driver programint main(){    int arr[] = {3, 5, 7, 9, 10, 90, 100, 130,                               140, 160, 170};    int ans = findPos(arr, 10);    if (ans==-1)        cout << "Element not found";    else        cout << "Element found at index " << ans;    return 0;}
// Java program to demonstrate working of// an algorithm that finds an element in an// array of infinite size class Test{    // Simple binary search algorithm    static int binarySearch(int arr[], int l, int r, int x)    {        if (r>=l)        {            int mid = l + (r - l)/2;            if (arr[mid] == x)                return mid;            if (arr[mid] > x)                return binarySearch(arr, l, mid-1, x);            return binarySearch(arr, mid+1, r, x);        }        return -1;    }         // Method takes an infinite size array and a key to be    // searched and returns its position if found else -1.    // We don't know size of arr[] and we can assume size to be    // infinite in this function.    // NOTE THAT THIS FUNCTION ASSUMES arr[] TO BE OF INFINITE SIZE    // THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKING    static int findPos(int arr[],int key)    {        int l = 0, h = 1;        int val = arr[0];         // Find h to do binary search        while (val < key)        {            l = h;     // store previous high            //check that 2*h doesn't exceeds array            //length to prevent ArrayOutOfBoundException            if(2*h < arr.length-1)               h = 2*h;                        else               h = arr.length-1;                         val = arr[h]; // update new val        }         // at this point we have updated low        // and high indices, thus use binary        // search between them        return binarySearch(arr, l, h, key);    }     // Driver method to test the above function    public static void main(String[] args)    {        int arr[] = new int[]{3, 5, 7, 9, 10, 90,                            100, 130, 140, 160, 170};        int ans = findPos(arr,10);                 if (ans==-1)            System.out.println("Element not found");        else            System.out.println("Element found at index " + ans);    }}
# Python Program to demonstrate working of an algorithm that finds# an element in an array of infinite size # Binary search algorithm implementationdef binary_search(arr,l,r,x):     if r >= l:        mid = l+(r-l)//2         if arr[mid] == x:            return mid         if arr[mid] > x:            return binary_search(arr,l,mid-1,x)         return binary_search(arr,mid+1,r,x)     return -1 # function takes an infinite size array and a key to be# searched and returns its position if found else -1.# We don't know size of a[] and we can assume size to be# infinite in this function.# NOTE THAT THIS FUNCTION ASSUMES a[] TO BE OF INFINITE SIZE# THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKINGdef findPos(a, key):     l, h, val = 0, 1, arr[0]     # Find h to do binary search    while val < key:        l = h            #store previous high        h = 2*h          #double high index        val = arr[h]       #update new val     # at this point we have updated low and high indices,    # thus use binary search between them    return binary_search(a, l, h, key) # Driver functionarr = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170]ans = findPos(arr,10)if ans == -1:    print ("Element not found")else:    print("Element found at index",ans)
// C# program to demonstrate working of an// algorithm that finds an element in an// array of infinite sizeusing System; class GFG {         // Simple binary search algorithm    static int binarySearch(int []arr, int l,                                int r, int x)    {        if (r >= l)        {            int mid = l + (r - l)/2;                         if (arr[mid] == x)                return mid;            if (arr[mid] > x)                return binarySearch(arr, l,                                   mid-1, x);                                                return binarySearch(arr, mid+1,                                       r, x);        }                 return -1;    }         // Method takes an infinite size array    // and a key to be searched and returns    // its position if found else -1. We    // don't know size of arr[] and we can    // assume size to be infinite in this    // function.    // NOTE THAT THIS FUNCTION ASSUMES    // arr[] TO BE OF INFINITE SIZE    // THEREFORE, THERE IS NO INDEX OUT    // OF BOUND CHECKING    static int findPos(int []arr,int key)    {        int l = 0, h = 1;        int val = arr[0];         // Find h to do binary search        while (val < key)        {            l = h;     // store previous high            h = 2 * h;// double high index            val = arr[h]; // update new val        }         // at this point we have updated low        // and high indices, thus use binary        // search between them        return binarySearch(arr, l, h, key);    }     // Driver method to test the above    // function    public static void Main()    {        int []arr = new int[]{3, 5, 7, 9,            10, 90, 100, 130, 140, 160, 170};        int ans = findPos(arr, 10);                 if (ans == -1)            Console.Write("Element not found");        else            Console.Write("Element found at "                            + "index " + ans);    }} // This code is contributed by nitin mittal.
<?php// PHP program to demonstrate working// of an algorithm that finds an// element in an array of infinite size // Simple binary search algorithmfunction binarySearch($arr, $l,                      $r, $x){    if ($r >= $l)    {        $mid = $l + ($r - $l)/2;        if ($arr[$mid] == $x)            return $mid;        if ($arr[$mid] > $x)            return binarySearch($arr, $l,                           $mid - 1, $x);        return binarySearch($arr, $mid + 1,                                   $r, $x);    }    return -1;} // function takes an infinite// size array and a key to be// searched and returns its// position if found else -1.// We don't know size of arr[]// and we can assume size to be// infinite in this function.// NOTE THAT THIS FUNCTION ASSUMES// arr[] TO BE OF INFINITE SIZE// THEREFORE, THERE IS NO INDEX// OUT OF BOUND CHECKINGfunction findPos( $arr, $key){    $l = 0; $h = 1;    $val = $arr[0];     // Find h to do binary search    while ($val < $key)    {                 // store previous high        $l = $h;                      // double high index        $h = 2 * $h;                 // update new val        $val = $arr[$h];    }     // at this point we have    // updated low and high    // indices, Thus use binary    // search between them    return binarySearch($arr, $l,                        $h, $key);}     // Driver Code    $arr = array(3, 5, 7, 9, 10, 90, 100,                 130, 140, 160, 170);    $ans = findPos($arr, 10);    if ($ans==-1)        echo "Element not found";    else        echo "Element found at index " , $ans; // This code is contributed by anuj_67.?>
<script>// JavaScript program to demonstrate working of an algorithm that finds// an element in an array of infinite size // Simple binary search algorithmfunction binarySearch(arr, l, r, x){    if (r>=l)    {        let mid = l + Math.floor((r - l)/2);        if (arr[mid] == x)            return mid;        if (arr[mid] > x)            return binarySearch(arr, l, mid-1, x);        return binarySearch(arr, mid+1, r, x);    }    return -1;} // function takes an infinite size array and a key to be// searched and returns its position if found else -1.// We don't know size of arr[] and we can assume size to be// infinite in this function.// NOTE THAT THIS FUNCTION ASSUMES arr[] TO BE OF INFINITE SIZE// THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKINGfunction findPos(arr, key){    let l = 0, h = 1;    let val = arr[0];     // Find h to do binary search    while (val < key)    {        l = h;     // store previous high        h = 2*h;     // double high index        val = arr[h]; // update new val    }     // at this point we have updated low and    // high indices, Thus use binary search    // between them    return binarySearch(arr, l, h, key);} // Driver program    let arr = [3, 5, 7, 9, 10, 90, 100, 130,                            140, 160, 170];    let ans = findPos(arr, 10);    if (ans==-1)        document.write("Element not found");    else        document.write("Element found at index " + ans);   // This code is contributed by Surbhi Tyagi.</script>
Output:  
Element found at index 4
Let p be the position of element to be searched. Number of steps for finding high index ‘h’ is O(Log p). The value of ‘h’ must be less than 2*p. The number of elements between h/2 and h must be O(p). Therefore, time complexity of Binary Search step is also O(Log p) and overall time complexity is 2*O(Log p) which is O(Log p).This article is contributed by Gaurav Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
nitin mittal
vt_m
shivamgoel009
UnniKrishnan5
surbhityagi15
dibyasadhukhan
Searching
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find largest element in an array
Given an array of size n and a number k, find all elements that appear more than n/k times
Search an element in a sorted and rotated array
k largest(or smallest) elements in an array
Median of two sorted arrays of different sizes
Find the index of an array element in Java
Most frequent element in an array
Count number of occurrences (or frequency) in a sorted array
Two Pointers Technique
Best First Search (Informed Search)