Binary Search in Java

Description: Typical binary search algorithm that searches an array of integers and returns the index of the found value. If the value is not found it returns -1.
Tested Platform: Java SE 7, Windows 7
Language: Java
// Takes in an array of integers, the value to search for and the lowest and 
// highest array indexes of the array. Returns the index of the found value or 
// returns -1 if no item is found.

public static int BinarySearch(int[] arNumbers, int searchValue, int min, int max) {
        while (max >= min) {
            int midpoint = (max - min) / 2 + min;
            
            if (searchValue > arNumbers[midpoint]) { min = midpoint + 1; }
            else if (searchValue < arNumbers[midpoint]) { max = midpoint - 1; }
            else { return midpoint; }
        }

        return -1;
}

Submitted: February 14, 2013

Return to the snippets listing