我正在尝试编写一些功能来实现 Hoare 的快速排序分区方案。我有我认为应该有效的功能,但我收到运行时错误:
TypeError: cannot unpack non-iterable int object
任何人都可以帮助我了解发生了什么以及如何解决它吗?谢谢!
def partition(arr, low, high):
comp = 0
swap = 0
pivot = arr[low]
i = low - 1
j = high + 1
while (True):
# Find leftmost element greater than
# or equal to pivot
i += 1
while (arr[i] < pivot):
comp += 1
i += 1
# Find rightmost element smaller than
# or equal to pivot
j -= 1
while (arr[j] > pivot):
comp+=1
j -= 1
# If two pointers met.
if (i >= j):
return j
swap += 1
arr[i], arr[j] = arr[j], arr[i]
def quicksort(A, lo, hi):
if lo >= 0 and hi >= 0 and lo < hi:
(comp, swap, p) = partition(A, lo, hi)
(lcomp, lswap) = quicksort(A, lo, p)
(rcomp, rswap) = quicksort(A, p + 1, hi)
return (comp + lcomp + rcomp, swap + lswap + rswap)
return (0,0)
def printArray(arr, n):
for i in range(n):
print(arr[i], end=" ")
print()
# Driver code
arr = [2,8,7,1,3,5,6,4]
n = len(arr)
print(quicksort(arr, 0, len(arr)-1))
print(arr)
我一直在思考为什么它不起作用,并且查看了类似的代码,只是看不出我遗漏了什么。我对 Python 比较陌生,所以如果这是一个简单的修复,请原谅我。