1. 程式人生 > >c# 二分查詢

c# 二分查詢

        /// <summary>
        /// 二分查詢法
        /// </summary>
        /// <param name="array">有序陣列</param>
        /// <param name="key">查詢的值</param>
        /// <returns>陣列中值的索引</returns>
        public static int BinaryChopSearch(int[] array, int key)
        {
            int
lo = 0; int hi = array.Length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (key < array[mid]) hi = mid - 1; else if (key > array[mid]) lo = mid + 1; else return mid; } return
-1; }