[英]Quicksort in Python
L = [7, 12, 1, -2, 0, 15, 4, 11, 9]
def quicksort(L, low, high):
if low < high:
pivot_location = Partition(L, low, high)
quicksort(L,low, pivot_location)
quicksort(L,pivot_location + 1, high)
return L
def Partition(L, low, high):
pivot = L[low]
leftwall = low
for i in range(low + 1, high, 1):
if L[i] < pivot:
temp = L[i]
L[i] = L[leftwall]
L[leftwall] = temp
leftwall += 1
temp = pivot
pivot = L[leftwall]
L[leftwall] = temp
return leftwall
print(quicksort(L, 0, len(L) - 1))
当我运行代码时,它将产生以下结果:[-2、0、1、4、7、11、12、15、9]。 一个要素处于错误的位置。 如果有人能告诉我问题出在哪里?
我只是更改了这一行代码,它运行良好:
quicksort(L, 0, len(L))
代替
quicksort(L, 0, len(L) - 1)
在这里,我仅向您展示在Python中实现Q_Sort的另一种简单方法:
def q_sort(lst):
return [] if not lst else q_sort([e for e in lst[1:] if e <= lst[0]]) + [lst[0]] + q_sort([e for e in lst[1:] if e > lst[0]])
L = [7, 12, 1, -2, 0, 15, 4, 11, 9]
print q_sort(L)
我们得到:
[-2,0,1,4,4,7,9,11,12,15]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.