0

I was studying algorithms and tried implementing quickSelect as explained here and asked here on StackOverflow.

I am curious as to why the code would return seemingly random result (instead of the expected k-th smallest element) when I wrote the code like this quickSelect(A2, k - len(A) - len(A2)) instead of like this quickSelect(A2, k - (len(A) - len(A2))). I've pasted the whole code and please feel free to uncomment/comment these two alternatives and run it. I thought the expressions like k - len(A) - len(A2) are evaluated BEFORE being passed into the next stack level?

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))
vvvvv
  • 25,404
  • 19
  • 49
  • 81
user1330974
  • 2,500
  • 5
  • 32
  • 60

0 Answers0