快速排序效果不佳 - Python 3
QuickSort does not work well - Python 3
我的快速排序有问题。他正在给我订购清单,但从我这里拿走了一些东西。我不知道错误是什么。
非常感谢你的帮助。
代码:
#QuickSort
def quickSort(lista):
if len(lista) < 2:
return lista
menores, medio, mayores = _partition(lista)
return quickSort(menores) + medio + quickSort(mayores)
def _partition(lista):
pivote = lista[0]
menores = []
mayores = []
for x in range(1,len(lista)-1):
if lista[x] < pivote:
menores.append(lista[x])
else:
mayores.append(lista[x])
return menores, [pivote], mayores
L = [6,7,-1,0,5,2,3,8]
print(quickSort(L))
结果:
[-1, 0, 5, 6, 7]
[Finished in 0.2s]
在每次调用 _partition
时,您删除最后一个元素,因为您使用
for x in range(1,len(lista)-1):
而不是
for x in range(1,len(lista)):
(range(1,n)
给出 [1,2,...(n-1)]
)
我的快速排序有问题。他正在给我订购清单,但从我这里拿走了一些东西。我不知道错误是什么。 非常感谢你的帮助。
代码:
#QuickSort
def quickSort(lista):
if len(lista) < 2:
return lista
menores, medio, mayores = _partition(lista)
return quickSort(menores) + medio + quickSort(mayores)
def _partition(lista):
pivote = lista[0]
menores = []
mayores = []
for x in range(1,len(lista)-1):
if lista[x] < pivote:
menores.append(lista[x])
else:
mayores.append(lista[x])
return menores, [pivote], mayores
L = [6,7,-1,0,5,2,3,8]
print(quickSort(L))
结果:
[-1, 0, 5, 6, 7]
[Finished in 0.2s]
在每次调用 _partition
时,您删除最后一个元素,因为您使用
for x in range(1,len(lista)-1):
而不是
for x in range(1,len(lista)):
(range(1,n)
给出 [1,2,...(n-1)]
)