Site Search:

Binary Search

Binary Search is a searching algorithm that find a key's rank in a sorted array with time complexity O(NlogN) and space complexity O(1).

Code:

public class BinarySearch {
    public static void main(String[] args) {
        int[] a = new int[]{1, 2, 4, 5, 6, 8, 11};
        int k = rank(5, a);
        System.out.println(k);
    }
    
    public static int rank(int k, int[] a) {
        int lo = 0;
        int hi = a.length - 1;
        while(lo <= hi) {
            int mid = lo + (hi - lo)/2;
            //...k..a[mid].....
            if(k < a[mid]) hi = mid - 1;
            else if(k > a[mid]) lo = mid + 1;
            else return mid;
        }
        return lo;
    }

}

Examples: