• 二分法算法


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

      

  • 相关阅读:
    React.js自学第一天
    优化的34条定律
    JS 打字机效果
    css3 翻书效果
    对象操作
    表单提交验证
    封装cookie组件
    iOS中为网站添加图标到主屏幕
    教你从Win8换回Win7
    关于VB中Print函数在数组中换行的理解
  • 原文地址:https://www.cnblogs.com/yjung/p/5672394.html
Copyright © 2020-2023  润新知