How to perform a binary search on IList?

前端 未结 11 1360
执念已碎
执念已碎 2020-11-28 09:32

Simple question - given an IList how do you perform a binary search without writing the method yourself and without copying the data to a type with bui

11条回答
  •  离开以前
    2020-11-28 10:24

    If you need a ready-made implementation for binary search on ILists, Wintellect's Power Collections has one (in Algorithms.cs):

    /// 
    /// Searches a sorted list for an item via binary search. The list must be sorted
    /// by the natural ordering of the type (it's implementation of IComparable<T>).
    /// 
    /// The sorted list to search.
    /// The item to search for.
    /// Returns the first index at which the item can be found. If the return
    /// value is zero, indicating that  was not present in the list, then this
    /// returns the index at which  could be inserted to maintain the sorted
    /// order of the list.
    /// The number of items equal to  that appear in the list.
    public static int BinarySearch(IList list, T item, out int index)
            where T: IComparable
    {
        // ...
    }
    

提交回复
热议问题