Skip to content

Instantly share code, notes, and snippets.

@vumaasha
Forked from anonymous/randomizedquicksort.py
Created March 8, 2012 02:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vumaasha/1998240 to your computer and use it in GitHub Desktop.
Save vumaasha/1998240 to your computer and use it in GitHub Desktop.
Randomized Quick Sort in python
from random import randint
def inPlaceQuickSort(A,start,end):
if start<end:
pivot=randint(start,end)
temp=A[end]
A[end]=A[pivot]
A[pivot]=temp
p=inPlacePartition(A,start,end)
inPlaceQuickSort(A,start,p-1)
inPlaceQuickSort(A,p+1,end)
def inPlacePartition(A,start,end):
pivot=randint(start,end)
temp=A[end]
A[end]=A[pivot]
A[pivot]=temp
newPivotIndex=start-1
for index in xrange(start,end):
if A[index]<A[end]:#check if current val is less than pivot value
newPivotIndex=newPivotIndex+1
temp=A[newPivotIndex]
A[newPivotIndex]=A[index]
A[index]=temp
temp=A[newPivotIndex+1]
A[newPivotIndex+1]=A[end]
A[end]=temp
return newPivotIndex+1
X=[4,5,7,4,3,6,0,4,22,45,82]
inPlaceQuickSort(X,0,len(X)-1)
#X=[0, 3, 4, 4, 4, 5, 6, 7, 22, 45, 82]
@aminbenarieb
Copy link

Why you choose random pivot twice: before inPlacePartition call and after?

@RuijieZ
Copy link

RuijieZ commented Dec 26, 2017

when u swap the pivot and the last element, you do not need to create extra variable temp. you only need to do the following:

A[end], A[pivot] = A[pivot], A[end]

@sap9433
Copy link

sap9433 commented Jan 30, 2018

I guess second randint in not required

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