13
13
14
14
15
15
def quick_sort (collection : list ) -> list :
16
- """A pure Python implementation of quick sort algorithm
16
+ """A pure Python implementation of quicksort algorithm.
17
17
18
18
:param collection: a mutable collection of comparable items
19
- :return: the same collection ordered by ascending
19
+ :return: the same collection ordered in ascending order
20
20
21
21
Examples:
22
22
>>> quick_sort([0, 5, 3, 2, 2])
@@ -26,23 +26,26 @@ def quick_sort(collection: list) -> list:
26
26
>>> quick_sort([-2, 5, 0, -45])
27
27
[-45, -2, 0, 5]
28
28
"""
29
+ # Base case: if the collection has 0 or 1 elements, it is already sorted
29
30
if len (collection ) < 2 :
30
31
return collection
31
- pivot_index = randrange (len (collection )) # Use random element as pivot
32
- pivot = collection [pivot_index ]
33
- greater : list [int ] = [] # All elements greater than pivot
34
- lesser : list [int ] = [] # All elements less than or equal to pivot
35
32
36
- for element in collection [:pivot_index ]:
37
- (greater if element > pivot else lesser ).append (element )
33
+ # Randomly select a pivot index and remove the pivot element from the collection
34
+ pivot_index = randrange (len (collection ))
35
+ pivot = collection .pop (pivot_index )
38
36
39
- for element in collection [pivot_index + 1 :]:
40
- (greater if element > pivot else lesser ).append (element )
37
+ # Partition the remaining elements into two groups: lesser or equal, and greater
38
+ lesser = [item for item in collection if item <= pivot ]
39
+ greater = [item for item in collection if item > pivot ]
41
40
41
+ # Recursively sort the lesser and greater groups, and combine with the pivot
42
42
return [* quick_sort (lesser ), pivot , * quick_sort (greater )]
43
43
44
44
45
45
if __name__ == "__main__" :
46
+ # Get user input and convert it into a list of integers
46
47
user_input = input ("Enter numbers separated by a comma:\n " ).strip ()
47
48
unsorted = [int (item ) for item in user_input .split ("," )]
49
+
50
+ # Print the result of sorting the user-provided list
48
51
print (quick_sort (unsorted ))
0 commit comments