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, 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 = 0;
    int max = arNumbers.length - 1;

    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;
}

Posted: March 17, 2023

Return to the snippets listing