我們使用最完整的泛型多載:
public static int BinarySearch<T>(
T[] array, int index, int length, T value, IComparer<T> comparer)
>= 0。~returnValue 為第一個大於 value 的元素索引(即插入點)。~returnValue 為 array.Length(插入尾部)。按位補碼 (~) 將正數變負、負數變正,對負數再補碼即得原值。此技巧將「未找到」與「插入位置」合二為一。
因 BinarySearch 需 IComparer<T>,且我們需在同一類別內切換升/降冪,故宣告巢狀 SortDirectionComparer<T>。使用 ListSortDirection 枚舉(Ascending/Descending)表達方向,Compare 內依方向乘以 -1 即可反轉。
本節程式碼可直接複製執行,驗證無誤後進入下一階段:元素新增與自動擴容。