Skip to content

Commit d9934ba

Browse files
Merge pull request #101 from vish-han/patch-3
search in Infinite Array Added
2 parents 46c7dd2 + 08aaa5e commit d9934ba

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//Question : You have to search for an element in an infinitely sorted array and return the position of the given element;
2+
3+
public class InfiniteArray {
4+
public static void main(String[] args) {
5+
int arr[]={1,3,4,5,6,8,12,31,34,45,67,123,231,454,676};
6+
System.out.println(ans(arr,123));
7+
}
8+
//you have to search in chunks in order to find the element , in order to do that you have to find the range in which your target element is there;
9+
static int ans(int nums[],int target){
10+
11+
int start=0;
12+
int end=1;
13+
while(nums[end]<target){
14+
int temp=end+1;
15+
end=end+(end-start+1)*2;
16+
start=temp;
17+
18+
}
19+
20+
return infiniteArray(nums,target,start,end);
21+
}
22+
//once we find the start and end of the range by above function we can apply normal binary search and find the position of given element;
23+
//if the target element is not there in the array the funcion will return -1;
24+
static int infiniteArray(int nums[],int target,int start ,int end){
25+
26+
27+
while (start <= end) {
28+
int mid = start + (end - start) / 2;
29+
if (target < nums[mid]) {
30+
end = mid - 1;
31+
} else if (nums[mid] < target) {
32+
start = mid + 1;
33+
} else return mid;
34+
}
35+
36+
return -1;
37+
}
38+
}

0 commit comments

Comments
 (0)