Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

position of an element in infinite sorted array

public class InfiniteArray {
  /*
  as the given array is infinite size, we need to find the range,
  where the target element lies.
  we exponentially double the size and checks if the target element greater
  than the array[end]. if true we return the boundaries as new start and end.
  */
  
    public static int[] FindRange(int[] array, int target) {
        int[] ranges = new int[2];
        int start = 0;
        int end = 1;
        while (target > array[end]) {
            int newStart = end+1;
            end = end + (end-start+1)*2;
            start = newStart;
        }
        ranges[0] = start;
        ranges[1] = end;
        return ranges;
    }
    public static int BinarySearch(int[] array, int target) {
        int[] rangeArray = FindRange(array, target);
        int start = rangeArray[0];
        int end = rangeArray[1];

        while (start <= end) {
            int mid = start + (end-start) / 2;
            if (array[mid] < target) start = mid+1;
            else end = mid-1;
            if (array[mid] == target) return mid;
        }
        return -1;
    }
    public static void main(String[] args) {
        int[] list  = new int[]{3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170};
        System.out.println(BinarySearch(list, 10)); // Output: 4
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: java float data type 
Java :: set up a tree in java 
Java :: different constructiors in java and what they do explained 
Java :: convert string into unicode java 
Java :: stream reduce 
Java :: can we have abstract class having no abstract method in java? 
Java :: java hex to rgb 
Java :: swagger ui java 
Java :: How to perform in-order traversal of a binary tree? 
Java :: Java Queue Linked List Implementation 
Java :: declaring java variables 
Java :: can we serialize class in java 
Java :: how to divide a double in java 
Java :: static method in non static class java 
Java :: java print array of objects 
Java :: for loop in java 
Java :: java to python 
Java :: how to Compile the source code in ./src folder with libraries in ./lib folder using JavaSE-1.7 
Java :: https://graph.instagram.com/14.0/10218560180051171 
Java :: java and python begineers mcq with answers 
Java :: how to set credentials for speechClient Java google api 
Java :: jbutton default color 
Java :: Which of the below is a correct identifier for a method name in Java * 2 points 0start #stop 0_start *start# 
Java :: exchangerate api 
Java :: java 8 lambda delete from list 
Java :: Iterating The Queue Elements 
Java :: how to use asynx task to make api connection java 
Java :: android string animation 
Java :: java 2d array previous object 
Java :: localdatetimw java input 
ADD CONTENT
Topic
Content
Source link
Name
9+8 =