这是我在python中尝试实现的快速排序
但是,我注意到有一个max call stack exceeded错误,可能是因为我的集合的长度永远不会下降。你知道吗
打印时,我注意到递归调用不会更新“end”变量
def swap(collection, index1, index2):
temp = collection[index1]
collection[index1] = collection[index2]
collection[index2] = temp
def partition(collection, idx1, idx2):
left = idx1
right = idx2
pivot = len(collection)//2
while(left < right):
while(collection[left] < collection[pivot]):
left += 1
while(collection[right] > collection[pivot]):
right -= 1
if left < right:
swap(collection, left, right)
left +=1
right -=1
return left
def quickSort(collection, start, end):
#Check for base case
if len(collection) > 1:
index = partition(collection, start, end)
newIdx = index - 1
if start < newIdx:
quickSort(collection, start, newIdx)
if index < right:
quickSort(collection, index, end)
return collection
array = [7,5, 10, 12, 3,2,9]
quickSort(array, 0, len(array) - 1)
print(array)
目前没有回答
相关问题 更多 >
编程相关推荐