Skip to content

Commit 13142f1

Browse files
committed
Improve quick_sort to avoid mutating input list
1 parent 2574004 commit 13142f1

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

sorts/quick_sort.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,15 @@
99
"""
1010

1111
from __future__ import annotations
12-
1312
from random import randrange
1413

1514

1615
def quick_sort(collection: list) -> list:
17-
"""A pure Python implementation of quicksort algorithm.
16+
"""Return a new list containing the sorted elements of the collection
17+
using the Quick Sort algorithm.
1818
19-
:param collection: a mutable collection of comparable items
20-
:return: the same collection ordered in ascending order
19+
:param collection: a list of comparable items
20+
:return: a new list sorted in ascending order
2121
2222
Examples:
2323
>>> quick_sort([0, 5, 3, 2, 2])
@@ -27,19 +27,23 @@ def quick_sort(collection: list) -> list:
2727
>>> quick_sort([-2, 5, 0, -45])
2828
[-45, -2, 0, 5]
2929
"""
30-
# Base case: if the collection has 0 or 1 elements, it is already sorted
30+
31+
# Base case: if list has 0 or 1 element it is already sorted
3132
if len(collection) < 2:
32-
return collection
33+
return collection.copy()
3334

34-
# Randomly select a pivot index and remove the pivot element from the collection
35+
# Select a random pivot
3536
pivot_index = randrange(len(collection))
36-
pivot = collection.pop(pivot_index)
37+
pivot = collection[pivot_index]
3738

38-
# Partition the remaining elements into two groups: lesser or equal, and greater
39-
lesser = [item for item in collection if item <= pivot]
39+
# Partition the elements
40+
lesser = [
41+
item for index, item in enumerate(collection)
42+
if item <= pivot and index != pivot_index
43+
]
4044
greater = [item for item in collection if item > pivot]
4145

42-
# Recursively sort the lesser and greater groups, and combine with the pivot
46+
# Recursively sort both partitions
4347
return [*quick_sort(lesser), pivot, *quick_sort(greater)]
4448

4549

@@ -48,5 +52,5 @@ def quick_sort(collection: list) -> list:
4852
user_input = input("Enter numbers separated by a comma:\n").strip()
4953
unsorted = [int(item) for item in user_input.split(",")]
5054

51-
# Print the result of sorting the user-provided list
52-
print(quick_sort(unsorted))
55+
# Print the sorted result
56+
print(quick_sort(unsorted))

0 commit comments

Comments
 (0)