二分查找/折半查找算法

  二分查找又称折半查找,优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,且插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。

class Program
{
    static void Main(string[] args)
    {
        int[] array = new[] { 23, 98, 234, 765, 974, 867, 86786, 145432, 8676343, 9999999 }; // 目标数组
        int findValue = 145432; // 被查找数
        
        Console.WriteLine(BinarySearch(array, findValue, 0, array.Length - 1) ? "被查找数存在数组array中" : "被查找数不存在数组array中");
        Console.ReadKey();
    }
    
    /// <summary>
    /// 二分查找/折半查找(分治思想、递归,目标数组必须是有序序列),算法复杂度为o(log(n),n代表目标数组长度)
    /// </summary>
    /// <param name="sources">目标数组</param>
    /// <param name="findValue">目标查找数</param>
    /// <param name="low">区间最小索引</param>
    /// <param name="high">区间最大索引</param>
    /// <returns>true:存在,false,不存在</returns>
    private static bool BinarySearch(int[] sources, int findValue, int low, int high)
    {
        // 未找到,终止递归
        if (low > high) return false;

        // 折半查找中间值 索引:(a + b) / 2表示算数平均数,即中点
        int middleIndex = (low + high) % 2 == 0 ? (low + high) / 2 : (low + high) / 2 + 1;

        if (findValue > sources[middleIndex])
        {
            // 大于中间值,在区间[middleIndex + 1, high]递归继续查找
            return BinarySearch(sources, findValue, middleIndex + 1, high);
        }
        if (findValue < sources[middleIndex])
        {
            // 小于中间值,在区间[low, middleIndex - 1]递归继续查找
            return BinarySearch(sources, findValue, low, middleIndex - 1);
        }

        // findValue 等于 sources[middleIndex],找到,终止递归
        return true;
    }
}
原文地址:https://www.cnblogs.com/GodX/p/4066005.html