问题
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