Skip to content

Commit 7329d5d

Browse files
authored
Create quicksort.py
1 parent 59ff87d commit 7329d5d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

divide_and_conquer/quicksort.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
def quicksort(arr: list) -> list:
2+
"""Quicksort function implementation in Python.
3+
4+
>>> quicksort([])
5+
[]
6+
7+
>>> quicksort([5])
8+
[5]
9+
10+
>>> quicksort([3, 6, 8, 10, 1, 2, 1, 3, 2, 8])
11+
[1, 1, 2, 2, 3, 3, 6, 8, 8, 10]
12+
"""
13+
14+
# If the length of the array is less than or equal to 1, then there's nothing to sort, so return the given array
15+
if len(arr) <= 1:
16+
return arr
17+
18+
# In quicksort a element needs to be selected as pivot, it can be anywhere
19+
# In this case let the pivot be the first element
20+
pivot = arr[0]
21+
22+
# Using list comprehension creating three list object: smaller_elemnts, pivot_elements & larger_elements based on the comparison with the pivot element
23+
smaller_elements = [x for x in arr if x < pivot]
24+
pivot_elements = [x for x in arr if x == pivot]
25+
larger_elements = [x for x in arr if x > pivot]
26+
27+
# Recursively splitting the list object to determine the correct position of the element
28+
return quicksort(smaller_elements) + pivot_elements + quicksort(larger_elements)
29+
30+
if __name__ == "__main__":
31+
import doctest
32+
doctest.testmod()

0 commit comments

Comments
 (0)