C# 二分查找

二分查找(折半查找):
优点:比较次数少,查找快,稳定,占用系统内存较少                                  
缺点:待查找的集合(数组)必须是有序,所以二分查找适用于不经常变动并且查找频率较多的序列中。
过程:找到集合的中间位置,来对比是否为所要查找的元素,如果是,查找结束,返回元素,如果不是,根据中间位置把集合分成前后两个子集合,再使用相同的方式,在子集合中进行查找,如果找到停止查找,一直到子集合为空,集合中没有要查找元素。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 二分查找
{
    class Program
    {
        
        static void Main(string[] args)
        {
            int[] y = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
            int rr = BinarySearch(y, 0, y.Length - 1, 8);
            Console.Write(rr);    //12
        }
        public static int BinarySearch(int[] arr, int low, int high, int key)
        {
            int mid = (low + high) / 2;
            if (low > high)
                return -1;
            else
            {
                if (arr[mid] == key)
                    return arr[mid];
                else if (arr[mid] > key)
                    return BinarySearch(arr, low, mid - 1, key);
                else
                    return BinarySearch(arr, mid + 1, high, key);
            }
        }
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值