1. 程式人生 > 其它 >.NET C#實現string型別List<T>二分查詢演算法功能(支援Contains模糊匹配)

.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

{

//沒有找到

}