Skip to content

Commit 19f8f23

Browse files
Position of element n Infinite sorted array
1 parent 7656af1 commit 19f8f23

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

InfiniteArray.java

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/* Given an infinite sorted array. Find position of element in this array */
2+
3+
4+
//since it is an infinite array therefore arr.length cannot be used to find end. But we need to find end for binary search. So we take chunks/small sizes of boxes for finding start end range
5+
6+
public class InfiniteArray {
7+
public static void main(String[] args) {
8+
int[] arr = {3, 5, 7, 9, 10, 90,
9+
100, 130, 140, 160, 170};
10+
int target = 10;
11+
System.out.println(ans(arr, target));
12+
}
13+
static int ans(int[] arr, int target) {
14+
// first find the range
15+
// first start with a box of size 2
16+
int start = 0;
17+
int end = 1;
18+
19+
// condition for the target to lie in the range
20+
while (target > arr[end]) {
21+
int temp = end + 1; // this is my new start
22+
23+
// double the box value
24+
// end = previous end + sizeofbox*2
25+
end = end + (end - start + 1) * 2;
26+
start = temp;
27+
}
28+
return binarySearch(arr, target, start, end);
29+
30+
}
31+
static int binarySearch(int[] arr, int target, int start, int end) {
32+
while(start <= end) {
33+
int mid = start + (end - start) / 2;
34+
35+
if (target < arr[mid]) {
36+
end = mid - 1;
37+
} else if (target > arr[mid]) {
38+
start = mid + 1;
39+
} else {
40+
return mid;
41+
}
42+
}
43+
return -1;
44+
}
45+
}

0 commit comments

Comments
 (0)