递归算法中Python列表的可变性

时间:2016-03-01 07:13:11

标签: python algorithm sorting recursion quicksort

我编写了这个就地快速排序算法,但修改后的数组没有传递给父调用。我是Python的新手,并不理解通过值/引用传递,可变/不可变的东西等。 任何解释指导都会很棒!

def quickSortPartition(a, l, r):
    if len(a) < 2:
        return a
    else:
        print a, l, r
        p = a[l]
        i = l + 1
        for j in range(l + 1, r+1):
            if a[j] < p:
                temp = a[i]
                a[i] = a[j]
                a[j] = temp
                i = i + 1
        temp = a[l]
        a[l] = a[i - 1]
        a[i - 1] = temp
        firstPartition = a[:i-1]
        pivot = a[i-1]
        secondPartition = a[i:]
        if len(a[:i-1]) > 1:
            quickSortPartition(a[:i-1], 0, len(a[:i-1])-1)
        if len(a[i:]) > 1:
            quickSortPartition(a[i:], 0, len(a[i:])-1)
        return a


lines = [3, 8, 2, 5, 1, 4, 7, 6]

# print lines
quickSorted = quickSortPartition(lines, 0, len(lines)-1)

print quickSorted

2 个答案:

答案 0 :(得分:3)

基本上,quickSortPartition返回一个已排序的列表,因此当您对quickSortPartition进行递归调用时,请确保捕获返回的值

def quickSortPartition(a, l, r):
    if len(a) < 2:
        return a
    else:
        print a, l, r
        p = a[l]
        i = l + 1
        for j in range(l + 1, r+1):
            if a[j] < p:
                temp = a[i]
                a[i] = a[j]
                a[j] = temp
                i = i + 1
        temp = a[l]
        a[l] = a[i - 1]
        a[i - 1] = temp
        firstPartition = a[:i-1]
        pivot = a[i-1]
        secondPartition = a[i:]
        if len(a[:i-1]) > 1:
            a[:i-1] = quickSortPartition(a[:i-1], 0, len(a[:i-1])-1)
        if len(a[i:]) > 1:
            a[i:] = quickSortPartition(a[i:], 0, len(a[i:])-1)
        return a


lines = [3, 8, 2, 5, 1, 4, 7, 6]

# print lines
quickSorted = quickSortPartition(lines, 0, len(lines)-1)

print quickSorted

输出:

[3, 8, 2, 5, 1, 4, 7, 6] 0 7
[1, 2] 0 1
[5, 8, 4, 7, 6] 0 4
[8, 7, 6] 0 2
[6, 7] 0 1
[1, 2, 3, 4, 5, 6, 7, 8]

答案 1 :(得分:1)

当您使用范围下标列表时,它会创建列表的副本并将其返回。

因此,当您将a[:i]传递给您的函数时,不会考虑任何更改。

执行a[i] = 3后,它会更改您的列表。

因此,您可能希望更改代码,以便您的函数可以直接作为输入和索引i。