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

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

           
        }
    }
}

 

posted on 2015-08-10 21:19  闫科达  阅读(244)  评论(0编辑  收藏  举报

导航