[英]How to implement quick sort using random pivot in python
So far I have this but when I try to print the result I just get a random list not the organized list, any idea of how can I solve it?到目前为止我有这个但是当我尝试打印结果时我只是得到一个随机列表而不是有组织的列表,我知道如何解决它吗?
import random
lista = [8,12,3,11,5,9,10,4,15,7]
def particionado(lista):
pivote = random.choice(lista)
menores = []
mayores = []
for i in range(1, len(lista)):
if lista[i] < pivote:
menores.append(lista[i])
else:
mayores.append(lista[i])
return quicksort(menores), pivote , quicksort(mayores)
def quicksort(lista):
if len(lista) < 2:
return lista
menores, pivote, mayores = particionado(lista)
return menores + [pivote] + mayores
# result
: quicksort(list)
: [7, 9, 9, 9, 9, 9, 9, 9, 9, 15]
You choose the pivot randomly, but here:您随机选择枢轴,但在这里:
for i in range(1, len(lista)):
you assume the pivot is in position zero.你假设枢轴在位置零。 What I'd suggest instead is this:我的建议是这样的:
pivote_idx = random.randrange(len(lista))
pivot = lista[pivote_idx]
for i in range(len(lista)):
if i == pivote_idx: continue
...
Alternatively you can swap the pivot to the first position in the list, but I assumed you can't modify the input since you intentionally don't do that.或者,您可以将枢轴交换到列表中的第一个位置,但我认为您无法修改输入,因为您故意不这样做。
This change should help.此更改应该有所帮助。
def particionado(lista):
pivote = random.choice(lista)
menores = []
mayores = []
for i in lista:
if i < pivote:
menores.append(i)
elif i > pivote:
mayores.append(i)
return quicksort(menores), pivote , quicksort(mayores)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.