Binary Search ImmutableArray - CSharp System

CSharp examples for System:Array Search

Description

Binary Search ImmutableArray

Demo Code

// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Collections.Generic;
using System;/* w ww  . ja  v  a  2s  . c om*/

public class Main{
        // same as Array.BinarySearch but the ability to pass arbitrary value to the comparer without allocation
      public static int BinarySearch<TElement, TValue>(this ImmutableArray<TElement> array, TValue value, Func<TElement, TValue, int> comparer)
      {
         int low = 0;
         int high = array.Length - 1;

         while (low <= high)
         {
            int middle = low + ((high - low) >> 1);
            int comparison = comparer(array[middle], value);

            if (comparison == 0)
            {
               return middle;
            }

            if (comparison > 0)
            {
               high = middle - 1;
            }
            else
            {
               low = middle + 1;
            }
         }

         return ~low;
      }
}

Related Tutorials