C#算法-二分搜索

二分搜索,折半搜索  binarySearch

前提: 一个有序的容器

1  4  7  9  12  25

下标 0 - 5 
最中间的数字: 左边的都比它小,右边的都比他大
(0+5)/2 -> 下标为2的是最中间的数字

二分搜索的核心就是,找中间的数字,确定要搜索的结果在左边还是右边,如果在左边,那么把左边那一部分继续进行二分搜索  直到 找到或者 找完为止

1、用while循环实现二分搜索,对普通数组进行搜索

        //用循环循环实现
        public static int BinarySearch(int[] arr, int left, int right, int target)
        {
            while (left <= right)
            {
                int midIndex = (left + right) / 2;
                if (target == arr[midIndex])
                {
                    return midIndex;
                }
                else if (target < arr[midIndex])
                {
                    right = midIndex - 1;
                }
                else if (target > arr[midIndex])
                {
                    left = midIndex + 1;
                }
            }
            return -1;
        }
        

2、用递归方式实现二分搜索,对List数组搜索 

       static int BinarySearch2<T>(List<T> list, int left, int right, T target) 
       where T : IComparable<T>
        {
            int midIndex = (left + right) / 2;
            if (left > right)
            {
                return -1;
            }

            int compareResult = list[midIndex].CompareTo(target);

            if (compareResult == 0)
            {
                return midIndex;
            }
            else if (compareResult < 0)
            {
                return BinarySearch2(list, midIndex + 1, right, target);
            }
            else
            {
                return BinarySearch2(list, left, midIndex - 1, target);
            }
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中的二分查找是一种高效的查找算法,它适用于已排序的数组或列表。下面是使用C#实现二分查找的步骤: 1. 确保数组或列表已排序。如果未排序,需要先对其进行排序。 2. 定义一个方法来执行二分查找。该方法接收三个参数:要查找的目标值、要查找的数组或列表、以及数组或列表的起始和结束索引。 3. 在方法内部,计算数组或列表的中间索引:(start + end) / 2。 4. 比较目标值与中间元素的值。如果相等,则返回中间索引。 5. 如果目标值小于中间元素的值,则在左半部分继续进行二分查找。更新结束索引为中间索引减1,并递归调用二分查找方法。 6. 如果目标值大于中间元素的值,则在右半部分继续进行二分查找。更新起始索引为中间索引加1,并递归调用二分查找方法。 7. 如果起始索引大于结束索引,则表示目标值不存在于数组或列表中,返回-1。 下面是一个示例代码: ```csharp public static int BinarySearch(int target, int[] array, int start, int end) { if (start > end) return -1; int mid = (start + end) / 2; if (array[mid] == target) return mid; else if (array[mid] > target) return BinarySearch(target, array, start, mid - 1); else return BinarySearch(target, array, mid + 1, end); } ``` 使用示例: ```csharp int[] array = { 1, 3, 5, 7, 9 }; int target = 5; int result = BinarySearch(target, array, 0, array.Length - 1); if (result != -1) Console.WriteLine("目标值在数组中的索引为:" + result); else Console.WriteLine("目标值不存在于数组中。"); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值