数组应用之————二分法查找

时间:2022-11-03 19:11:39
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _99
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] dns = new int[] { 3, 8, 9, 10, 16, 28, 36, 42, 58, 79, 98, 99 };
            Console.Write("输入你要查找的数");
            int n = Convert.ToInt32(Console.ReadLine());

            int top, bottom, mid;
            top = 0;

            bottom = dns.Length - 1;
            while (bottom>=top )
            {
                mid = (top + bottom) / 2;
                int k = dns[mid];
                if (k < n) 
                {
                    top = mid + 1;
                }
                else if (k > n) 
                {
                bottom=mid-1;
                }else
                {
                    Console .WriteLine ("你找的值在"+mid+"位置");
                    break;              
                }
                Console.ReadLine();
            }

           
        }
    }
}