简体   繁体   English

具有时间复杂度O(lg n)的搜索函数

[英]Search function with time complexity O(lg n)

I needed to create a search function with time complexity O(lgn) that would return the position that a certain value x would go in a tuple. 我需要创建一个具有时间复杂度O(lgn)的搜索函数,该函数将返回某个值x将进入元组的位置。

For example, search(8, (2, 7, 12)) would return 2, 例如, search(8, (2, 7, 12))将返回2,
search(-5, (2, 3, 4, 10)) would return 0 and search(-5, (2, 3, 4, 10))将返回0并
search(6, (4, 6, 12)) would return 1. with the tuple already sorted search(6, (4, 6, 12))将返回1.元组已经排序
I wrote the following code: 我写了以下代码:

    def search(x,seq):
        for i in seq:
            if x<i:
                return seq.index(i)
            elif x == i:
                return seq.index(i)
            elif x>seq[-1]:
                return (seq.index(seq[-1]))+1

Does this code have time complexity O(lgn)? 该代码是否具有时间复杂度O(lgn)?

Your current solution is O(n) . 您当前的解决方案是O(n)

Since you mentioned a tuple will always be in a sorted order, you can apply binary search , which runs in O(lg(n)) , to find the appropriate index. 由于您提到了一个元组将始终处于排序顺序,因此您可以应用在O(lg(n))运行的二进制搜索来找到适当的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM