zoukankan      html  css  js  c++  java
  • 二分查找法&大O表示法

    二分查找法的输入是一个有序的元素列表,如果要查找的元素包含在列表中,二分查找返回其位置,否则返回null

    Python代码(来源于《算法图解》一书):

    def binary_search(list, item):
        low = 0
        high = len(list)-1
        while low <= high:
            mid = (low + high)//2
            guess = list[mid]
            if guess == item:
                return mid
            if guess < item:
                low = mid + 1
            else:
                high = mid - 1
        return None

    测试:

    >>>binary_search(my_list, 3)
                
    1

    C#代码(因为我平时多用C#):

    namespace Algorithms
    {
        public static class BinarySearch
        {
            public static int Binary_Search(List<double>list, double item)
            {
                int low = 0;
                int high = list.Count - 1;
                while(low <= high)
                {
                    int mid = (low + high) / 2;
                    double guess = list[mid];
                    if (guess == item)
                        return mid;
                    else if (guess < item)
                        low = mid + 1;
                    else
                        high = mid - 1;
                }
                return -1;
            }
        }
    }

    大O表示法:

    用于表示算法的速度有多快。O(n),n表示最糟的情况下的操作数。5种经常遇到的大O运行时间。

    • O(log n) 对数时间,比如二分法;
    • O(n) 线性时间,比如简单查找;
    • O(n*log n) 包括快速排序法(后面说);
    • O(n^2) 选择排序
    • O(n!) 旅行商问题的解决方案。

    https://blog.csdn.net/weixin_38483589/article/details/84147376

    关于大O表示法,上面这篇文章写的很详细。

  • 相关阅读:
    es6 学习笔记
    正则表达式 学习笔记
    knockout 学习笔记
    错误笔记
    zepto 学习笔记
    Dialog提示框
    setContentView( )方法
    SVG图形之几何图形——学习笔记2
    SVG图形之SVG文件如何嵌入HTML文档——学习笔记1
    getchar()的用法
  • 原文地址:https://www.cnblogs.com/larissa-0464/p/10623403.html
Copyright © 2011-2022 走看看