Skip to content

Commit bb2f1fb

Browse files
authored
searchinInfiniteArrayAdded
1 parent 04ad1aa commit bb2f1fb

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
static int infiniteArray(int nums[],int target,int start ,int end){
23+
24+
25+
while (start <= end) {
26+
int mid = start + (end - start) / 2;
27+
if (target < nums[mid]) {
28+
end = mid - 1;
29+
} else if (nums[mid] < target) {
30+
start = mid + 1;
31+
} else return mid;
32+
}
33+
34+
return -1;
35+
}
36+
}

0 commit comments

Comments
 (0)