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);
            }
        }


    }

   

}


你可能感兴趣的:(c#,数据结构,C#二分查找)