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.
// an element in an array of infinite size
// Simple binary search algorithm
functionbinarySearch(arr, l, r, x)
let mid = l + Math.floor((r - l)/2);
if(arr[mid] == x)
if(arr[mid] > x)
returnbinarySearch(arr, l, mid-1, x);
returnbinarySearch(arr, mid+1, r, x);
// 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 CHECKING
let l = 0, h = 1;
let val = arr;
// 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
returnbinarySearch(arr, l, h, key);
// Driver program
let arr = [3, 5, 7, 9, 10, 90, 100, 130,
140, 160, 170];
let ans = findPos(arr, 10);
document.write("Element not found");
document.write("Element found at index "+ ans);
// This code is contributed by Surbhi Tyagi.
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
Approach: The problem can be solved based on the following observation:
Since array is sorted we apply binary search but the length of array is infinite so that we take start = 0 and end = 1 .
After that check value of target is greater than the value at end index,if it is true then change newStart = end + 1 and newEnd = end +(end – start +1)*2 and apply binary search .
Otherwise , apply binary search in the old index values.
Please Login to comment...