instagram

Java Binary Search

This is small article about implementation of binary search in Java

public class BinarySearch {

	public static void main(String args[]) {
		int[] i = { 2, 4, 6, 7, 8, 9, 10 };
		if (binarySearch(i, 10)) {
			System.out.println("Found");
		} else {
			System.out.println("NOT Found");
		}
	}

	public static boolean binarySearch(int[] array, int searchIt) {

		int low = 0;
		int high = array.length;

		while (low < high) {

			int middle = (low + high) / 2;
			int middleInt = array[middle];

			if (searchIt < middleInt) {
				high = middle - 1;
			} else if (searchIt > middleInt) {
				low = middle + 1;
			} else {
				return true;
			}

		}

		return false;

	}

}
Share