Skip to content

Added quick sort algorithm in python #130

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

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
39 changes: 39 additions & 0 deletions SortingAlgorithms/quick_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# 'Quick Sort'
# Randomize Pivot to avoid worst case, currently pivot is last element


def quickSort(A, si, ei):
if si < ei:
pi = partition(A, si, ei)
quickSort(A, si, pi-1)
quickSort(A, pi+1, ei)


# 'Partition'
# Utility function for partitioning the array(used in quick sort)
def partition(A, si, ei):
x = A[ei] # x is pivot, last element
i = (si-1)
for j in range(si, ei):
if A[j] <= x:
i += 1
A[i], A[j] = A[j], A[i]
A[i+1], A[ei] = A[ei], A[i+1]
return i+1


# Alternate Implementation
# Warning --> As this function returns the array itself, assign it to some
# Variable while calling. Example--> sorted_arr=quicksort(arr)
# 'Quick sort'


def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) / 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)