Ejemplo n.º 1
0
        private static int Binary <T>(Get <T> get, int index, int length, CompareToExpectedValue <T> compare)
        {
            int low = index;
            int hi  = index + length - 1;

            while (low <= hi)
            {
                int median = low + (hi - low >> 1);
                switch (compare(get(median)))
                {
                case Comparison.Equal:
                    return(median);

                case Comparison.Less:
                    low = median + 1;
                    break;

                case Comparison.Greater:
                    hi = median - 1;
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
            return(~low);
        }
Ejemplo n.º 2
0
 /// <summary>Performs a binary search to find the index where a specific value fits in indexed, sorted items.</summary>
 /// <param name="get">Indexer delegate.</param>
 /// <param name="length">The number of indexed items.</param>
 /// <param name="compare">Comparison delegate.</param>
 /// <returns>The index where the specific value fits into the index, sorted items.</returns>
 public static int BinarySearch(Get <T> get, int length, CompareToExpectedValue <T> compare)
 {
     if (get == null)
     {
         throw new System.ArgumentNullException("get");
     }
     if (compare == null)
     {
         throw new System.ArgumentNullException("compare");
     }
     return(BinarySearch(get, 0, length, compare));
 }
Ejemplo n.º 3
0
 /// <summary>Performs a binary search to find the index where a specific value fits in indexed, sorted items.</summary>
 /// <param name="get">Indexer delegate.</param>
 /// <param name="length">The number of indexed items.</param>
 /// <param name="compare">Comparison delegate.</param>
 /// <returns>The index where the specific value fits into the index, sorted items.</returns>
 public static int Binary <T>(Get <T> get, int length, CompareToExpectedValue <T> compare)
 {
     if (get is null)
     {
         throw new ArgumentNullException(nameof(get));
     }
     if (compare is null)
     {
         throw new ArgumentNullException(nameof(compare));
     }
     if (length <= 0)
     {
         throw new ArgumentOutOfRangeException(nameof(length), length, "!(" + nameof(length) + " > 0)");
     }
     return(Binary(get, 0, length, compare));
 }