Skip to content

Adding quick sort variant where random pivot point is chosen #774

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

Merged
merged 1 commit into from
Apr 30, 2019
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
33 changes: 33 additions & 0 deletions sorts/random_pivot_quick_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""
Picks the random index as the pivot
"""
import random

def partition(A, left_index, right_index):
pivot = A[left_index]
i = left_index + 1
for j in range(left_index + 1, right_index):
if A[j] < pivot:
A[j], A[i] = A[i], A[j]
i += 1
A[left_index], A[i - 1] = A[i - 1], A[left_index]
return i - 1

def quick_sort_random(A, left, right):
if left < right:
pivot = random.randint(left, right - 1)
A[pivot], A[left] = A[left], A[pivot] #switches the pivot with the left most bound
pivot_index = partition(A, left, right)
quick_sort_random(A, left, pivot_index) #recursive quicksort to the left of the pivot point
quick_sort_random(A, pivot_index + 1, right) #recursive quicksort to the right of the pivot point

def main():
user_input = input('Enter numbers separated by a comma:\n').strip()
arr = [int(item) for item in user_input.split(',')]

quick_sort_random(arr, 0, len(arr))

print(arr)

if __name__ == "__main__":
main()