Does python have a sorted list?

前端 未结 7 1926
温柔的废话
温柔的废话 2020-11-29 20:16

By which I mean a structure with:

  • O(log n) complexity for x.push() operations
  • O(log n) complexity to find an element
  • O(n) comple
7条回答
  •  野性不改
    2020-11-29 20:32

    Though I have still never checked the "big O" speeds of basic Python list operations, the bisect standard module is probably also worth mentioning in this context:

    import bisect
    L = [0, 100]
    
    bisect.insort(L, 50)
    bisect.insort(L, 20)
    bisect.insort(L, 21)
    
    print L
    ## [0, 20, 21, 50, 100]
    
    i = bisect.bisect(L, 20)
    print L[i-1], L[i]
    ## 20, 21
    

    PS. Ah, sorry, bisect is mentioned in the referenced question. Still, I think it won't be much harm if this information will be here )

    PPS. And CPython lists are actually arrays (not, say, skiplists or etc) . Well, I guess they have to be something simple, but as for me, the name is a little bit misleading.


    So, if I am not mistaken, the bisect/list speeds would probably be:

    • for a push(): O(n) for the worst case ;
    • for a search: if we consider the speed of array indexing to be O(1), search should be an O(log(n)) operation ;
    • for the list creation: O(n) should be the speed of the list copying, otherwise it's O(1) for the same list )

    Upd. Following a discussion in the comments, let me link here these SO questions: How is Python's List Implemented and What is the runtime complexity of python list functions

提交回复
热议问题