I'm currently doing an assignment for my computer science class, and I can't figure out what is wrong with my code to perform quick select.
def partition(a_list, first, last):
pivot = a_list[last]
i = first-1
for j in range(first, last):
if a_list[j] <= pivot:
i += 1
a_list[i], a_list[j] = a_list[j], a_list[i]
a_list[i+1], a_list[last] = a_list[last], a_list[i+1]
print(a_list)
return i+1
def selection(a_list, first, last, k):
pivot = a_list[last]
pivotIndex = partition(a_list, first, last)
if first == last:
return a_list[k]
elif k <= pivotIndex:
return selection(a_list, first, pivotIndex-1, k)
else:
return selection(a_list, pivotIndex+1, last, k - pivotIndex)
print(selection([5,4,1,10,8,3,2], 0, 6, 1))
print(selection([5,4,1,10,8,3,2], 0, 6, 3))
print(selection([5,4,1,10,8,3,2], 0, 6, 6))
print(selection([5,4,1,10,8,3,2], 0, 6, 7))
print(selection([46, 50, 16, 88, 79, 77, 17, 2, 43, 13, 86, 12, 68, 33, 81, \
74, 19, 52, 98, 70, 61, 71, 93, 5, 55], 0, 24, 19))
After the third print statement my code just get stuck in a loop, and eventually dies because maximum recursions have been reached. The first output should also be 1, and I understand why it's doing that. But I can't figure out a solution to fix it.
This is my output, before it eventually gives me the error maximum recursion depths reached. (Ignore the list being printed, it's just there so I can see what it's partitioning)
[1, 2, 5, 10, 8, 3, 4]
2
[1, 2, 5, 10, 8, 3, 4]
[1, 2, 3, 4, 8, 5, 10]
3
[1, 2, 5, 10, 8, 3, 4]
[1, 2, 3, 4, 8, 5, 10]
[1, 2, 3, 4, 8, 5, 10]
[1, 2, 3, 4, 5, 8, 10]
[1, 2, 3, 5, 4, 8, 10]
[1, 2, 3, 4, 5, 8, 10]
[1, 2, 3, 5, 4, 8, 10]
[1, 2, 3, 4, 5, 8, 10]