J'ai le code python ci-dessous pour l'algorithme Quicksort. Le code fonctionne bien jusqu'à ce que tous les éléments vers la droite du pivot soient plus grands que le pivot, auquel cas ils restent non triés.L'implémentation Python de Quicksort échoue à trier le tableau entier
En théorie, le code doit trier tous les éléments du tableau, mais à ce stade je ne sais pas ce que je suis absent
def swap(array, i, j):
temp = array[i]
array[i] = array[j]
array[j] = temp
def choosePivotFirstElement(array, left, right):
return left
def partition(array, pivotIndex, left, right):
swap(array, pivotIndex, left) #put pivot to the left
pivot = array[left]
i = left + 1
for j in range(left+1, right+1):
if (array[j] < pivot):
swap(array, i, j)
i = i + 1
swap(array, left, i-1) #put pivot back to its place
return (i-1) #return the position of the pivot
def qsort(array, left, right):
if ((right - left) < 2):
return
pivotIndex = choosePivotFirstElement(array, left, right)
split = partition(array, pivotIndex, left, right)
qsort(array, left, split)
qsort(array, split + 1, right)
return array
myList = [7,2,5,1,29,6,4,19,11]
sorted = qsort(myList,0,len(myList)-1)
print sorted
cela devrait retourner
[1, 2, 4, 5 , 6, 7, 11, 19, 29]
retourne à la place
[1, 2, 4, 5, 6, 7, 29, 19, 11]
Je suis novice en python, alors je pourrais faire une erreur assez évidente.
'qsort' ne renvoie rien ... il semble trier sur place. Votre déclaration 'print' ne montre-t-elle pas' None'? – Cameron
Êtes-vous sûr de cette condition '((droite - gauche) <2)'? à première vue, il semblerait que cela empêcherait votre tri, disons 'qsort ([1, 0], 0, 1)' – njzk2
De plus, swaps en python ca peut être accompli via 'x [i], x [j] = x [j], x [i] 'où' x' est votre liste. –