Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create QuickSort.py #297

Merged
merged 1 commit into from
Oct 12, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Create QuickSort.py
  • Loading branch information
Pulkit-100 authored Oct 11, 2020
commit 762056d664507ec74c1f4e2dc0ff387c1f30efbe
32 changes: 32 additions & 0 deletions Python/Algorithms/QuickSort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Python program for implementation of QuickSort with imporoved partition3 algorithm
def partition3(A,l,r):
pivot = A[l] # Taking leftmost element as pivot element
m1 = l
m2 = r
i = l
while i<=m2:
if A[i]==pivot:
i+=1
elif A[i]<pivot:
A[i],A[m1] = A[m1],A[i]
m1+=1
elif A[i]>pivot:
A[i],A[m2] = A[m2],A[i]
m2-=1
return m1,m2 # m1,m2 are the start and end position of the pivot element in array


def quickSort(A,l,r):
if l>=r:
return
m1,m2 = partition3(A,l,r)
quickSort(A,l,m1-1) # sort left part of the pivot
quickSort(A,m2+1,r) # sort right part of the pivot


# driver code to test the above code
if __name__ == '__main__':
n = int(input())
A = [int(j) for j in input().split()]
quickSort(A,0,n-1)
print(*A)