Java Binary Search binarySearch(int[] array, int key)

Here you can find the source of binarySearch(int[] array, int key)

Description

binary Search

License

Open Source License

Declaration

public static int binarySearch(int[] array, int key) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static int binarySearch(int[] array, int key) {

        return privateBinarySearch(array, 0, array.length - 1, key);
    }//from   w w  w.j  av a  2s .  co  m

    public static int binarySearch(int[] array, int leftBorder, int rightBorder, int key) {
        boundsTest(array.length, leftBorder, rightBorder);
        return privateBinarySearch(array, leftBorder, rightBorder, key);
    }

    private static int privateBinarySearch(int[] array, int leftBorder, int rightBorder, int key) {
        while (leftBorder <= rightBorder) {
            int currentPosition = (leftBorder + rightBorder) / 2;
            if (key < array[currentPosition]) {
                rightBorder = currentPosition - 1;
            } else if (key > array[currentPosition]) {
                leftBorder = currentPosition + 1;
            } else {
                return currentPosition;
            }
        }
        return -1;
    }

    private static void boundsTest(int arrayLength, int leftBorder, int rightBorder) {
        if (leftBorder < 0) {
            throw new ArrayIndexOutOfBoundsException("leftBorder index < 0: " + leftBorder);
        }
        if (rightBorder >= arrayLength) {
            throw new ArrayIndexOutOfBoundsException(
                    "rightBorder index > number of arrays elements : " + rightBorder);
        }
        if (leftBorder > rightBorder) {
            throw new IllegalArgumentException("leftBorder > rightBorder which is illegal!");
        }
    }
}

Related

  1. binarySearch(final double[] array, final double val)
  2. binarySearch(final Enum[] full, final int[] partial, final char key, final int index)
  3. binarySearch(final Object[] a, final int fromIndex, final int toIndex, final Object key)
  4. binarySearch(int arr[], int low, int high, int key)
  5. binarySearch(int codePoint)
  6. binarySearch(int[] array, int size, int value)
  7. binarySearch(int[] array, int size, int value)
  8. binarySearch(int[] index, int key, int begin, int end)
  9. binarySearch(int[] source, int key)