forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort.py
More file actions
Latest commit
48 lines (36 loc) · 1.39 KB
/
Copy pathquick_sort.py
File metadata and controls
48 lines (36 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
A pure Python implementation of the quick sort algorithm
For doctests run following command:
python3 -m doctest -v quick_sort.py
For manual testing run:
python3 quick_sort.py
"""
from __future__ importannotations
fromrandomimportrandrange
defquick_sort(collection: list) ->list:
"""A pure Python implementation of quick sort algorithm
:param collection: a mutable collection of comparable items
:return: the same collection ordered by ascending
Examples:
>>> quick_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> quick_sort([])
[]
>>> quick_sort([-2, 5, 0, -45])
[-45, -2, 0, 5]
"""
iflen(collection) <2:
returncollection
pivot_index=randrange(len(collection)) # Use random element as pivot
pivot=collection[pivot_index]
greater: list[int] = [] # All elements greater than pivot
lesser: list[int] = [] # All elements less than or equal to pivot
forelementincollection[:pivot_index]:
(greaterifelement>pivotelselesser).append(element)
forelementincollection[pivot_index+1 :]:
(greaterifelement>pivotelselesser).append(element)
return [*quick_sort(lesser), pivot, *quick_sort(greater)]
if__name__=="__main__":
user_input=input("Enter numbers separated by a comma:\n").strip()
unsorted= [int(item) foriteminuser_input.split(",")]
print(quick_sort(unsorted))