DEV Community

Niels Swimburger.NET πŸ”
Niels Swimburger.NET πŸ”

Posted on • Originally published at swimburger.net on

Generic Binary Search in C# .NET

Early this year, I decided to brush up on my algorithms and data structure knowledge. I took these great two courses (1, 2) on PluralSight by Robert Horvick.

To practice what I learned in this course, I decided to create generic versions of the different algorithms and data structures.

What do I mean by generic versions? These types of courses always use integers or strings to demonstrate the algorithms. Instead of using those primitive data types, I'm reimplementing the algorithms and data structures using C#'s generic type parameters.

Here's a console application with a generic method BinarySearch to perform a binary search on an enumerable:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        var r = new Random();
        var numbers = Enumerable.Range(0, 1000)
          .Select(x => r.Next(0, 1000))
          .Concat(new int[] {777})
          .Distinct()
          .OrderBy(x => x)
          .ToArray();

        var indexOf777 = Array.IndexOf(numbers, 777);
        Console.WriteLine($"Array.IndexOf: {indexOf777}");
        indexOf777 = BinarySearch(numbers, 777);
        Console.WriteLine($"Binary Search: {indexOf777}");
    }

    private static int BinarySearch<T>(IEnumerable<T> list, T needle) where T : IComparable
    {
        int left = 0;
        int right = list.Count() - 1;

        while (left <= right)
        {
            int median = (left + right) / 2;
            T item = list.ElementAt(median);

            var comparison = needle.CompareTo(item);
            if(comparison == 0)
            {
                return median;
            }

            if (comparison < 0)
            {
                right = median - 1;
            }
            else
            {
                left = median + 1;
            }
        }

        return -1;
    }
}
Enter fullscreen mode Exit fullscreen mode

By using a generic type parameter with the constraint that the type has to implement the IComparable interface, you can perform the binary search algorithm without knowing the exact type you are working with.

If you want to understand the logic behind the binary search algorithm, I recommend checking out the courses mentioned earlier. There's also a lot of other great resources out there online!

Disclaimer: This code works, but is only developed for the sake of practice. Use at your own risk or just use a sorting library. If you see some room for improvement, there most likely is, I'm all ears~

Top comments (0)