Binary Search in C#

Description: The typical binary search algorithm that searches an array of integers and returns the index of the value if found. Otherwise it returns -1.
Tested Platform: .NET 4.6, Visual Studio 2015, Windows 7/10
Language: C#
// 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