Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python code for the Quick Sort Algorithm
def quicksort(x):
if len(x) == 1 or len(x) == 0:
return x
pivot = x[0]
i = 0
for j in range(len(x)-1):
if x[j+1] < pivot:
x[j+1],x[i+1] = x[i+1], x[j+1]
i += 1
x[0],x[i] = x[i],x[0]
first_part = quicksort(x[:i])
second_part = quicksort(x[i+1:])
return first_part + second_part
alist = [54,26,93,17,77,31,44,55,20]
Copy link

ajitkshirsagar commented Mar 13, 2019

I think that you could re-write to something like this also:

def quicksort(x):
      if len(x) < 2:
          return x
          pivot = x[0]
          less = [i for i in x[1:] if i <= pivot]
          greater = [i for i in x[1:] if i > pivot]
          return quicksort(less) + [pivot] + quicksort(greater)

I think you are 2 times traversing the list.

Copy link

conectcell commented Jun 29, 2019

quicksort([8, 3, 1, 7, 0, 10, 2]) and it doesn't work

Copy link

CcGaviria commented Jun 30, 2019

Bueno pues la razón de que no funcione es que no estamos teniendo en cuenta el tipo de dato que comparamos:
The data type is not integer...

def sort(num):
if len(num) < 2:
return num
piv = int(num[0])
less = [x for x in num[1:] if int(x) < piv]
higher = [x for x in num[1:] if int(x) > piv]
return sort(higher) + [piv] + sort(less)
for y in range(0, input()):
list = raw_input()
alist = list.split()
listOrg = sort(alist)

Copy link

anandrajB commented Jan 24, 2020

simple method

a= [4,7,1,2,3,9,7,0,4,56,3]
for i in range(len(a)):
for j in range(len(a)):
if a[i]<a[j]:
print("The sorted list is ",a)

Copy link

RaviPabari commented Aug 19, 2020

@pete312 use pypy3 instead of python to see some BIG RUNNING TIME DIFFRENCE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment