为什么我的quicksort功能在Python中不起作用?

这是我的代码:

def quicksort(arr):
    if len(arr) > 1:
        left = []
        right = []

        for i in range(1, len(arr)):
            if arr[i] < arr[0]:
                left.append(arr[i])
            else:
                right.append(arr[i])

        quicksort(left)
        quicksort(right)

        arr = left + [arr[0]] + right

It worked before, however I tried to simplify the code a bit by not returning arr but rather changing it in the function. Now it does not work anymore. Any reasons why?

评论
  • 已注销
    已注销 回复

    运行以下代码行时:

    arr = left + [arr[0]] + right
    

    You're rebinding the name arr to a local value, and the connection to the original argument is lost.

  • 少黑
    少黑 回复

    这是一个范围界定问题。在Python中,一旦您使用赋值“ =”运算符,它将假定您不再与所讨论的原始对象有任何关系。

    Lets say arr originally had a reference of 361 (simplified) when it entered the function. Now if you changed a single element of the object, it's reference in memory would still be 361, hence the element would be changed in the original object. But your line arr = left + [arr[0]] + right now creates the local variable arr, which inside the function would have a reference of lets say 366. Now, any changes made to this variable do not transfer to the original arr, reference 361.

    因为您不再返回此变量,所以不能对原始对象进行任何更改。