Python - What is the space complexity when tuple swap is used in bubble sorting?

此生再无相见时 提交于 2021-01-28 10:09:39

问题


Consider the following bubble sort program:

arr = map(int, raw_input().split(' '))
print "Unsorted: \n{arr_name}".format(arr_name = arr)

for j in range(len(arr) - 1, 0, -1):
    for i in range(j):
        if (arr[i] > arr[i + 1]):
            arr[i], arr[i + 1] = arr[i +1], arr[i]

print "Sorted: \n{arr_name}".format(arr_name = arr)

Usually a temp variable is used for sorting and that would be mean a space complexity of 0(1). But my understanding is that, tuple swap is only a reassignment of identifiers to objects (link). Does this require any additional space? What would be the space complexity here? Is it still O(1) because a tuple is created?


回答1:


Actually the swap gets optimized (in CPython, at least) so that no tuple is created:

>>> def f():
...     a,b = b,a
... 
>>> dis(f)
  2           0 LOAD_FAST                0 (b)
              3 LOAD_FAST                1 (a)
              6 ROT_TWO             
              7 STORE_FAST               1 (a)
             10 STORE_FAST               0 (b)
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE 

It is still O(1), yes. Even if a tuple were created, it would still be O(1) since the tuple can be released immediately after the swap is performed.

The only extra memory being used is the stack space for holding the values to be swapped (which may not even be anything extra, since the maximum stack depth without the swap will probably already be enough). Then, the ROT_TWO opcode performs the swap:

    TARGET(ROT_TWO) {
        PyObject *top = TOP();
        PyObject *second = SECOND();
        SET_TOP(second);
        SET_SECOND(top);
        FAST_DISPATCH();
    }

Notice that no additional memory needs to be used; the top two stack elements are simply swapped. top and second above act as temporary variables.



来源:https://stackoverflow.com/questions/44462635/python-what-is-the-space-complexity-when-tuple-swap-is-used-in-bubble-sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!