My Code
public class InfiniteElement{
public static void main(String[] args) {
int[] arr = {1, 2, 4, 6, 8, 9, 10 , 13, 16, 19, 20 ,23, 27, 40, 42, 44};
int target = 44;
System.out.print(findPos(arr, target));
}
static int findPos(int[] arr, int target){
int start = 0;
int end = 1;
while(target > arr[end]){
//temp will the new start
int temp = end + 1;
//instead of breaking the box we are multiplying
//so that the chunk of boxes increase the window
//it will help us to find the target in particular boxes
// end = end + (end - start + 1) * 2;
// + 1 is because we are using the indices
end = end + (end - start + 1) * 2;
start = temp;
}
return binarySearch(arr, target, start, end);
}
static int binarySearch(int[] arr, int target, int start, int end){
while(start <= end){
int mid = start + (end - start) / 2;
if(arr[mid] == target){
return mid;
} else if(arr[mid] > target){
end = mid - 1;
} else{
start = mid + 1;
}
}
return -1;
}
}
I want anyone to find the error and rectify it. Thank a lot community.
Hey folks, how are you doing. This is from Kunal Kushwaha video for Binary Search Problem Solving 1:28:03 Q5 : Position of an Element in Infinite Sorted Array.
When the array is arr = {1, 2, 4, 6, 8, 9, 10, 13, 16, 19, 20 ,23, 27, 40, 42, 44}, target = 44;
I get error like: Array index out of bound. If anyone finds the solution, please let me.
New contributor
UDAYA KRISHNAN.M is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.