Skip to content

Instantly share code, notes, and snippets.

@bezzad
Last active October 22, 2019 07:07
Show Gist options
  • Save bezzad/84790e55bb7eb0b1ade7eea78510ddde to your computer and use it in GitHub Desktop.
Save bezzad/84790e55bb7eb0b1ade7eea78510ddde to your computer and use it in GitHub Desktop.
Binary search implementation to search a value of type T1 within a list of T2 type which comparable by value argument.
using System;
using System.Collections.Generic;
public static class Helper
{
/// <summary>
/// Searches a section of the list for a given element using a binary search
/// algorithm.
/// </summary>
/// <param name="items">list of <see cref="TItems"/>, which must be searched within</param>
/// <param name="index">offset to beginning search</param>
/// <param name="count">count of elements must be searched after offset</param>
/// <param name="value">the value of type <see cref="TValue"/> to search</param>
/// <returns>Found your value index in list</returns>
public static int BinarySearch<TItems, TValue>(this IList<TItems> items, int index, int count, TValue value)
where TItems : IComparable<TValue>
{
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)));
if (items.Count - index < count)
throw new ArgumentException("Argument has invalid len from index for count");
var lo = index;
var hi = index + count - 1;
// ReSharper disable once TooWideLocalVariableScope
int mid; // declared here for performance
while (lo <= hi)
{
mid = (lo + hi) / 2;
var r = items[mid].CompareTo(value);
if (r == 0)
return mid;
if (r < 0)
hi = mid - 1;
else
lo = mid + 1;
}
// return bitwise complement of the first element greater than value.
// Since hi is less than lo now, ~lo is the correct item.
return ~lo;
}
/// <summary>
/// Searches a section of the list for a given element using a binary search
/// algorithm.
/// </summary>
public static int BinarySearch<TItems, TValue>(this IList<TItems> items, TValue value)
where TItems : IComparable<TValue>
{
return items.BinarySearch(0, items.Count, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment