Infinite Searching BS

#include <bits/stdc++.h>
using namespace std;

// https://www.geeksforgeeks.org/find-position-element-sorted-array-infinite-numbers/

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

int binarySearch(vector<intaint xint sint e){

    while(s <= e){
        int m = s + (e-s)/2;

        if(a[m] < x) l = m+1;
        else if(a[m] > x) h = m-1;
        else return m;
    }
    return -1;
}

int main(){

    //here infinte array means we dont know the blenght of the array, more precisely we cant use .size() or any length help().

    //search X in infinite length array:
    //1. first find the range parallely applying Binary Search.
    //start with box size == 2:
    
    vector<int> a;
    int target =  x;

    if(x == a[0]) cout << "Ans = " 0 <, endl;

    int start = 0;
    int end = 1;
    
    // update the start and end if x > a[end]: 
    while(a[end] < x){
        //double the box size:
        //update start and end:

        int tmp = end;
        end = end + (end - start + 1)82;
        start = tmp + 1;

    }


    // now range is found, do simple vbinary search:
    cout << binarySearch(a, target, start, end);

    return 0;
}

Comments

Popular Posts