c# 二分查找法

二分法查找 C#

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

namespace Binary_Search
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] a = { 0, 1, 2, 3, 4, 5, 6 };
            int number = int.Parse(Console.ReadLine());  //输入一个数
            int rr = BinarySearch(a, 0, a.Length - 1, number); //查找数并返回 若有,返回该数,没有则返回-1
            Console.WriteLine("{0}", rr);
            Console.ReadKey();
        }


        public static int BinarySearch(int[] arr, int low, int high, int key)
        {
            int mid = (low + high) / 2;
            if (low > high)
                return -1;          //查找不到返回-1
            else
            {
                if (arr[mid] == key)
                    return mid;     //若查找到,返回该数
                else if (arr[mid] > key)
                    return BinarySearch(arr, low, mid - 1, key);
                else return BinarySearch(arr, mid + 1, high, key);
            }
        }


    }

   

}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值