Skip to content

Create quicksort.py #11748

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

Closed
wants to merge 4 commits into from
Closed
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
37 changes: 37 additions & 0 deletions divide_and_conquer/quicksort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
def quicksort(arr: list) -> list:
"""Quicksort function implementation in Python.

https://en.wikipedia.org/wiki/Quicksort
>>> quicksort([])
[]
>>> quicksort([5])
[5]
>>> quicksort([3, 6, 8, 10, 1, 2, 1, 3, 2, 8])
[1, 1, 2, 2, 3, 3, 6, 8, 8, 10]
"""

# If the length of the array is less than or equal to 1, then there's
# nothing to sort, so return the given array
if len(arr) <= 1:
return arr

# In quicksort a element needs to be selected as pivot, it can be anywhere
# In this case let the pivot be the first element
pivot = arr[0]

# Using list comprehension creating three list object: smaller_elemnts,
# pivot_elements & larger_elements
# based on the comparison with the pivot element
smaller_elements = [x for x in arr if x < pivot]
pivot_elements = [x for x in arr if x == pivot]
larger_elements = [x for x in arr if x > pivot]

# Recursively splitting the list object to determine the correct
# position of the element
return quicksort(smaller_elements) + pivot_elements + quicksort(larger_elements)


if __name__ == "__main__":
import doctest

doctest.testmod()