• 二分查找算法(C#实现)


    想了解这个算法是因为在最近面试的时候看到了二分查找算法的时候懵比了,所以回来就要恶补一下

      那么什么是二分查找算法呢.

        看名称就知道它是一半一半的找的,有点类似快速排序算法

         举个例子就是:有一个数组int[] array=new int[]{1,3,4,5,6,7};我们要找6这个数

          第一次:中间数是4    6比4大,所以下一次需要找4右边的数

          第二次:中间数是6    刚好

    我们来看一下C#的实现

            public static int fen(int[] array,int low,int high,int key)
            {
                int middle = (low + high) / 2;
                if (low>high)
                {
                    return 1;
                }
                else
                {
                    if (array[middle]==key)
                    {
                        return middle;
                    }
                    else if (array[middle] > key)
                    {
                        return fen(array, low, middle - 1, key);
                    }
                    else
                    {
                        return fen(array, middle+1, high, key);
                    }
                }
            }
            static void Main(string[] args)
            {
                int[] array = new int[] {1,2,3,4,5,6,7,8,9,10 };
                var t=fen(array, 0, array.Length - 1, 9);
                Console.WriteLine(t);
                Console.Read();
            }

    Hold on, everything is possible.
  • 相关阅读:
    python 中 print函数的用法详解
    可转债操作一览
    Python基本数据类型
    python的列表
    理财的方法
    92、Multiple commands produce Info.plist 报错
    91、最新cocoaPods安装与使用
    90、引入头文件不提示
    89、instancetype和id的区别
    88、const、static、extern介绍
  • 原文地址:https://www.cnblogs.com/student-note/p/6782205.html
Copyright © 2020-2023  润新知