码迷,mamicode.com
首页 > 其他好文 > 详细

二分法

时间:2015-05-22 23:47:31      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

namespace 二分法
{
    class Program
    {
        static void Main(string[] args)
        {
            //二分法前提:数组必须是有序的。
            int[] a = new int[] { 3, 4, 6, 8, 9, 10, 13, 16 };
            Console.WriteLine("请输入你想要找的数:");
            int find = Convert.ToInt32(Console.ReadLine());
            int top, bottom, mid; //定义上限下标,下线下标,中间下标
            top = 0;
            bottom = a.Length - 1;

            while (bottom>=top)
            {
                //算中间坐标
                mid = (bottom + top) / 2;
                //取中间的值
                int n = a[mid];
                if(n<find)
                {
                    top = mid + 1;
                }
                else if (n > find)
                {
                    bottom = mid - 1;
                }
                else
                {
                    Console.WriteLine("找到了,是第"+(mid+1)+"个数");
                    break;
                }
                
            }
            Console.ReadLine();
        }
    }
}

 

二分法

标签:

原文地址:http://www.cnblogs.com/lk-kk/p/4523401.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!