Skip to content

Instantly share code, notes, and snippets.

@george-silva
Created June 17, 2013 19:57
Show Gist options
  • Select an option

  • Save george-silva/5799796 to your computer and use it in GitHub Desktop.

Select an option

Save george-silva/5799796 to your computer and use it in GitHub Desktop.
def partition(v, left, right):
i = left
for j in range(left + 1, right + 1):
if v[j] < v[left]: # Se um elemento j for menor que o pivo
i += 1 # .. incrementa-se i
v[i], v[j] = v[j], v[i] # .. e troca o elemento j de posicao o elemento i
v[i], v[left] = v[left], v[i] # O pivo e' colocado em sua posicao final
return i
def quicksort(v, left, right):
if right > left: # Verifica se a lista tem 2 ou mais itens
pivotIndex = partition(v, left, right) # Pega a posicao do pivo
quicksort(v, left, pivotIndex - 1) # Ordena recursivamente os itens menores que o pivo
quicksort(v, pivotIndex + 1, right) # Ordena recursivamente os itens maiores que o pivo
'''
Exemplo de uso
>>> a = [4, 2, 4, 6, 3, 2, 5, 1, 3]
>>> quicksort(a, 0, len(a)-1)
>>> print a
>>> [1, 2, 2, 3, 3, 4, 4, 5, 6]
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment