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的补码。这样当查找失败是得时候既能返回一个负值,又能再次对返回
                //值求补得到插入点信息进行插入操作。
    
            }
        }
       
    
    }
  • 相关阅读:
    今日小结 5.7
    今日小结 5.2
    今日小结 4.30
    今日小结 4.29
    设计模式 笔记1
    第一次找实习
    Java入门 任务表
    今日小结 4.24
    今日小结 4.18
    今日小结 4.17
  • 原文地址:https://www.cnblogs.com/zhanjindong/p/3515241.html
Copyright © 2011-2022 走看看