Created
September 24, 2020 01:44
-
-
Save tannergooding/4136a33625fdcf79c5a8d59d7383780b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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