简体   繁体   中英

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.

For example, search(8, (2, 7, 12)) would return 2,
search(-5, (2, 3, 4, 10)) would return 0 and
search(6, (4, 6, 12)) would return 1. with the tuple already sorted
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)?

Your current solution is 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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