在Python中快速选择实现具有不确定的结果

时间:2015-11-20 04:09:42

标签: python algorithm

我正在研究算法并尝试按照here的说明实现quickSelect,并在StackOverflow上询问here

我很好奇为什么当我编写像quickSelect(A2, k - len(A) - len(A2))这样的代码而不是像quickSelect(A2, k - (len(A) - len(A2)))这样的代码时,代码会返回看似随机的结果(而不是预期的第k个最小元素)。我已粘贴整个代码,请随意取消注释/评论这两个备选方案并运行它。我认为像k - len(A) - len(A2)这样的表达式在被传递到下一个堆栈级别之前会被评估吗?感谢先进的答案!

import random
def quickSelect(A, k):
    if not A:
        return

    pivot = random.choice(A)

    A1 = []
    A2 = []

    for i in A:
        if i < pivot:
            A1.append(i)
        else:
            A2.append(i)

    if k < len(A1):
        return quickSelect(A1, k)
    elif k > (len(A) - len(A2)):
        # commented code below gives wrong results
        # return quickSelect(A2, k - len(A) - len(A2))
        return quickSelect(A2, k - (len(A) - len(A2)))
    else:
        return pivot

myList = [54,26,93,17,77,31,44,55,20]
# ordered array looks like this
# [17, 20, 26, 31, 44, 54, 55, 77, 93]
print(quickSelect(myList, 1))
print(quickSelect(myList, 2))
print(quickSelect(myList, 3))
print(quickSelect(myList, 4))
print(quickSelect(myList, 5))

0 个答案:

没有答案