.NET C#实现string类型List<T>二分查找算法功能(支持Contains模糊匹配)

工作中用到了二分查找功能,二分查找在数据量稍微大一些的情况下,优势比较明显,数据量如果很小,和顺序查找没啥太大区别。

二分查找算法具有前置条件的,集合必须是升序有序的。否则查找出来的结果是不正确的。自己以List<T>为基础封装一个自带升序排序功能的SortedList<T>,然后使用SortedList<T>再调用二分查找方法即可。

0.准备

using System.Collections.Generic;

 /// <summary>
    /// 自带排序功能的List<T>,方便二分查找时使用
    /// </summary>
    public class SortedList<T> : List<T>
    {
        /// <summary>
        /// 自带排序功能的添加方法
        /// </summary>
        /// <param name="item">数据项</param>
        public new void Add(T item)
        {
            int position = this.BinarySearch(item);//调用.NETFramework自己的BinarySearch实现
            if (position < 0)
            {
                position = ~position;
            }

            this.Insert(position, item);
        }

        /// <summary>
        /// 自带排序功能的修改方法
        /// </summary>
        /// <param name="item">新数据项</param>
        /// <param name="index">被修改数据项的位置下标</param>
        public void ModifySorted(T item, int index)
        {
            this.RemoveAt(index);

            int position = this.BinarySearch(item);//调用.NETFramework自己的BinarySearch实现
            if (position < 0)
            {
                position = ~position;
            }

            this.Insert(position, item);
        }
    }

1.直接上工具类。

public static class BinarySearchExtension
    {
        public static int BinarySearch(List<string> myArray, string key, bool isIncludeContains = false)
        {
            int lower = 0;
            int upper = myArray.Count - 1;
            int middleIndex;
            while (lower <= upper)
            {
                middleIndex = (lower + upper) / 2;
                if (myArray[middleIndex].Equals(key))
                {
                    return middleIndex;
                }

                if (isIncludeContains)
                {
                    if (myArray[middleIndex].Contains(key))
                    {
                        return middleIndex;
                    }
                }

                if (new CaseInsensitiveComparer().Compare(myArray[middleIndex], key) > 0)
                {
                    upper = middleIndex - 1;
                }
                else
                {
                    lower = middleIndex + 1;
                }
            }

            if (key == myArray[lower])
            {
                return lower;
            }
            if (isIncludeContains)
            {
                if (myArray[lower].Contains(key))
                {
                    return lower;
                }
            }

            return -1;
        }
    }

 

2.调用方式

var sortedList = new SortedList<string>(){“aaa","dddd","a","321","0","xxxx"};

var targetIndex = BinarySearchExtension.BinarySearch(sortedList,"MatchedString",true);

if (targetIndex >= 0)

{

//找到了

}

else

{

//没有找到

}

posted @ 2022-03-31 11:16  jeff151013  阅读(685)  评论(0编辑  收藏  举报