binary search in csharp

To perform a binary search in C#, you can use the Array.BinarySearch method or write your own binary search algorithm. Here's an example using the Array.BinarySearch method:

main.cs
int[] numbers = { 1, 5, 7, 9, 11, 13, 15 };
int key = 9;

int index = Array.BinarySearch(numbers, key);

if (index >= 0)
{
    Console.WriteLine("Element found at index: " + index);
}
else
{
    Console.WriteLine("Element not found");
}
237 chars
14 lines

In the example above, we have an array numbers containing sorted integer values. We want to search for the key value using binary search. The Array.BinarySearch method returns the index of the element if found, and a negative value if the element is not found. We then check if the index is non-negative to determine if the element was found or not.

If you prefer to implement your own binary search algorithm, here's a basic example:

main.cs
int BinarySearch(int[] array, int key)
{
    int left = 0;
    int right = array.Length - 1;

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

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

    return -1; // Element not found
}

int[] numbers = { 1, 5, 7, 9, 11, 13, 15 };
int key = 9;

int index = BinarySearch(numbers, key);

if (index >= 0)
{
    Console.WriteLine("Element found at index: " + index);
}
else
{
    Console.WriteLine("Element not found");
}
669 chars
40 lines

In this example, the BinarySearch method takes an array and a key value as parameters. It uses a while loop to repeatedly divide the search space in half until the key value is found or the search space is empty. The method returns the index of the element if found, or -1 if the element is not found.

related categories

gistlibby LogSnag