首页 > 编程语言 > 详细

二分法算法

时间:2016-07-15 09:38:30      阅读:235      评论:0      收藏:0      [点我收藏+]

 

 

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            int[] iArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
            for (int i = 0; i < iArray.Length; i++)
                Console.Write(iArray[i] + ",");
            Console.WriteLine("请输入您要查找的数字:");
            int ikey = Convert.ToInt32(Console.ReadLine());
            Program bs = new Program();
            int iResult = bs.iBinarySearch(ikey, iArray);
            Console.WriteLine(iResult);
            Console.ReadLine();
            return;
        }

        public int iBinarySearch(int key, int[] iArray)
        {
            int iLeft = 0;
            int iRight = iArray.Length - 1;
            while (iLeft <= iRight)
            {
                int iMiddle = (iLeft + iRight) / 2;
                if (key == iArray[iMiddle])
                    return iMiddle;
                else if (key > iArray[iMiddle])
                    iLeft = iMiddle + 1;
                else
                    iRight = iMiddle - 1;
            }
            return -1;
        }
    }
}

  

二分法算法

原文:http://www.cnblogs.com/yjung/p/5672394.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!