binary sort in csharp

Here's an example implementation of binary search in C#:

main.cs
public static int BinarySearch(int[] arr, int x)
{
    int left = 0;
    int right = arr.Length - 1;

    while (left <= right)
    {
        int mid = (left + right) / 2;

        if (arr[mid] == x)
        {
            return mid;
        }
        else if (arr[mid] < x)
        {
            left = mid + 1;
        }
        else
        {
            right = mid - 1;
        }
    }

    return -1;
}
409 chars
26 lines

This method takes an integer array arr and the value x that we want to search for. The method initializes two pointers left and right, with left pointing to the first element of the array and right pointing to the last element of the array.

It then enters a while loop and continues to search while left is less than or equal to right. Inside the loop, it calculates the midpoint mid of the array and checks if the mid element is equal to x. If it is, then mid is returned as the index of x in the array.

If arr[mid] is less than x, then the x must be in the right half of the array, so left is updated to be mid + 1. Otherwise, the x must be in the left half of the array, so right is updated to be mid - 1.

If the while loop completes without finding x, then -1 is returned to indicate that x was not found in the array.

Note that the binary search algorithm assumes that the array is sorted in ascending order. If the array is not sorted, then the results of the search will be unpredictable.

gistlibby LogSnag