Here you can find the source of binarySearch(int[] array, int key)
public static int binarySearch(int[] array, int key)
//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!"); } } }