Skip to content

Instantly share code, notes, and snippets.

@tannergooding
Created September 24, 2020 01:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tannergooding/4136a33625fdcf79c5a8d59d7383780b to your computer and use it in GitHub Desktop.
Save tannergooding/4136a33625fdcf79c5a8d59d7383780b to your computer and use it in GitHub Desktop.
using System;
using System.Runtime.CompilerServices;
public interface IComparer<T>
{
int CompareTo(T other);
}
public static class ArrayExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int BinarySearch<T, TComparer>(this T[] data, TComparer comparer)
where TComparer : IComparer<T>
{
int lo = 0;
int hi = data.Length - 1;
while (lo <= hi)
{
int i = (int)(((uint)hi + (uint)lo) >> 1);
int c = comparer.CompareTo(data[i]);
if (c == 0)
{
return i;
}
else if (c > 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int BinarySearch<T>(this T[] data, Func<T, int> compareTo)
{
int lo = 0;
int hi = data.Length - 1;
while (lo <= hi)
{
int i = (int)(((uint)hi + (uint)lo) >> 1);
int c = compareTo(data[i]);
if (c == 0)
{
return i;
}
else if (c > 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
}
public struct Int32Comparer : IComparer<int>
{
private readonly int _value;
public Int32Comparer(int value)
{
_value = value;
}
public int CompareTo(int other)
{
return _value.CompareTo(other);
}
}
public class MyExample
{
public static int Example1(int[] data)
{
return data.BinarySearch(new Int32Comparer(1));
}
public static int Example2(int[] data)
{
return data.BinarySearch((other) => 1.CompareTo(other));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment