zoukankan      html  css  js  c++  java
  • 基本算法实现(C#)

    二分查找

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Bsearch
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[] arr={1,2,3,4,5,6,7,8,9,10,11};//二分查找的对象是一个已经有序的顺序表
                int r = Bsearch(arr,11);
                Console.WriteLine(r);
                Console.WriteLine(Array.BinarySearch(arr,11));
            }
            public static int Bsearch(int[] arr,int key)
            {
                int low = 0, high = arr.Length - 1;
                while (low <= high)
                {
                    int mid = (low + high)>> 1;//Array内部的二叉查找就是通过右移来实现整除
                    if (key == arr[mid]) return mid;
                    else if (key < arr[mid])
                        high = mid - 1;
                    else
                        low = mid + 1;
                }
                return ~low;
                //当所查找的值不存在的时候,low指针会指向一个合适的查找关键字的插入位置,为了既能表示查找的关键字不存在
                //又能保存查找关键字的插入点,所以返回low的补码。这样当查找失败是得时候既能返回一个负值,又能再次对返回
                //值求补得到插入点信息进行插入操作。
    
            }
        }
       
    
    }
  • 相关阅读:
    import()函数
    node-sass安装报错
    npm 安装扩展模块时,因缓存报错的问题汇总
    测试
    export default 和 export 区别
    正则
    物联网
    第十二次课堂总结
    第十二次作业
    作业10
  • 原文地址:https://www.cnblogs.com/zhanjindong/p/3515241.html
Copyright © 2011-2022 走看看