【发布时间】:2021-05-12 08:41:03
【问题描述】:
这是用 Python3 编写的。这是代码:
def partition(arr, l, h):
pivot = arr[l]
i = l+1
j = h
while i <= j:
print('i is ', i)
print('j is ', j)
while arr[i] < pivot:
i += 1
while arr[j] > pivot:
j -= 1
arr[i], arr[j] = arr[j], arr[i]
# Placing the pivot at its sorted position
arr[j], arr[l] = pivot, arr[j]
return j
def quicksort(arr, l, h):
if l >= h:
return arr
p = partition(arr, l, h)
print('p is ', p)
quicksort(arr, l, p-1)
quicksort(arr, p+1, h)
test = [4, 2, 7, 1]
sorted_test = quicksort(test, 0, len(test)-1)
print(sorted_test)
根据错误,arr[i] 超出范围,但变量“i”如何达到该值? 我知道还有其他方法可以实现这一点,但我在这里做错了什么?
【问题讨论】:
-
看起来您正在增加
i,直到它超出您的列表末尾并尝试访问arr[i] -
@khelwood 是的,我想通了。但我不明白这是怎么回事。变量“i”不应达到该值。
-
好的。那么当您拥有
while arr[i] < pivot: i += 1时,什么会阻止i达到该值? -
@khelwood
while i<=j将确保i不超过j。而 j 可以保持的最大值是len(arr)-1我想错了吗? -
但是
while i<=j不会打断while arr[i] < pivot: i += 1。直到下一次外循环重复时,才会再次检查外循环条件。
标签: python python-3.x algorithm sorting quicksort