首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

打造可逆向排序的泛型字典類 (二):排序方向比較器實作

     編輯:關於C語言

利用 Array.BinarySearch 實現有序插入

Array.BinarySearch<T>(array, index, length, value, comparer) 回傳值編碼了插入位置:

  • >= 0:找到重複 Key,不可插入。
  • < 0:未找到,按位補碼 (~index) 即為插入索引。

內建排序方向比較器

實作 IComparer<T> 的巢狀類別 SortDirectionComparer<T>,封裝 ListSortDirection 枚舉:

public class SortDirectionComparer<T> : IComparer<T>
{
    private ListSortDirection _sortDir = ListSortDirection.Ascending;

    public SortDirectionComparer() { }
    public SortDirectionComparer(ListSortDirection dir) { _sortDir = dir; }

    public ListSortDirection SortDirection
    {
        get { return _sortDir; }
        set { _sortDir = value; }
    }

    public int Compare(T lhs, T rhs)
    {
        int result = lhs.ToString().CompareTo(rhs.ToString()); // 簡易示範,實務應用 IComparable<T>
        if (_sortDir == ListSortDirection.Descending) result *= -1;
        return result;
    }
}

版本 0.2 完整程式碼

包含靜態建構子初始化空陣列、預設建構子、Capacity 屬性與比較器。測試用 Main 僅驗證編譯通過。

public class ReversibleSortedList<TKey, TValue>
{
    #region 成員變數
    private TKey[] keys = new TKey[0];
    private TValue[] values;
    private static TKey[] emptyKeys;
    private static TValue[] emptyValues;
    #endregion

    #region 建構子
    static ReversibleSortedList()
    {
        emptyKeys = new TKey[0];
        emptyValues = new TValue[0];
    }
    public ReversibleSortedList()
    {
        this.keys = emptyKeys;
        this.values = emptyValues;
    }
    #endregion

    public int Capacity => this.keys.Length;

    #region SortDirectionComparer 定義 (同上)
    // ...
    #endregion
}

下一步將實作 Add、自動擴容與二分搜尋插入邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved