Searching element in sorted infinite array GFG
package com.company;
public class SearchingInInfiniteArray {
public static int binarySearching(int[] arr, int x, int l, int h) {
int n = arr.length;
int low = l; int high = h;
while(low <= high) {
int mid =(low + high) / 2;
if(arr[mid] == x){
return mid;
}
else if (arr[mid] < x) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return -1;
}
// Searching an element in an infinite array
// Recursive approach
public static int search(int[] arr, int x, int index) {
if (arr[index] == x) {
return index;
} else if (arr[index + 1] > x && arr[index] < x) {
return -1;
} else {
return search(arr, x, index + 1);
}
}
//Iterative approach
public static int searching(int[] arr, int x) {
int i = 0;
while (true) {
if (arr[i] == x) {
return i;
}
if (arr[i] > x) {
return -1;
}
i++;
}
}
// Efficient solution
public static int getIndex(int[] arr, int x) {
int i = 1;
if (arr[0] == x) {
return 0;
}
if(arr[1] == x){
return 1}
while(arr[i] < x) {
i = 2 * i;
if(arr[i] == x){
return i;
}
}
return binarySearching(arr, x, i / 2 + 1, i -1);
}
public static void main(String[] args) {
int[] array = new int[10001];
array[0] = 20;
array[1] = 40;
array[2] = 100;
array[3] = 300;
array[4] = 400;
System.out.println(getIndex(array, 300));
}
}
Comments
Post a Comment