Skip to content

Commit 93f9bf0

Browse files
committed
Improve selection sort doctests and documentation
- Add detailed algorithm description explaining the approach - Document time complexity O(n²) and space complexity O(1) - Add 11 comprehensive doctest examples covering: - Basic cases (already covered) - Edge cases (single element, empty list) - Sorted/reverse-sorted inputs - Lists with duplicates - Verification against standard library sorted() function These improvements help new learners understand the algorithm better and verify correctness across diverse inputs.
1 parent 2574004 commit 93f9bf0

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

sorts/selection_sort.py

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,15 @@ def selection_sort(collection: list[int]) -> list[int]:
22
"""
33
Sorts a list in ascending order using the selection sort algorithm.
44
5-
:param collection: A list of integers to be sorted.
6-
:return: The sorted list.
5+
Selection sort divides the input list into a sorted and unsorted region.
6+
It repeatedly finds the minimum element from the unsorted region and
7+
places it at the end of the sorted region.
8+
9+
Time Complexity: O(n²) in all cases
10+
Space Complexity: O(1)
11+
12+
:param collection: A list of comparable items to be sorted.
13+
:return: The same list sorted in ascending order.
714
815
Examples:
916
>>> selection_sort([0, 5, 3, 2, 2])
@@ -14,6 +21,30 @@ def selection_sort(collection: list[int]) -> list[int]:
1421
1522
>>> selection_sort([-2, -5, -45])
1623
[-45, -5, -2]
24+
25+
>>> selection_sort([1])
26+
[1]
27+
28+
>>> selection_sort([5, 4, 3, 2, 1])
29+
[1, 2, 3, 4, 5]
30+
31+
>>> selection_sort([1, 2, 3, 4, 5])
32+
[1, 2, 3, 4, 5]
33+
34+
>>> selection_sort([3, 3, 3, 3])
35+
[3, 3, 3, 3]
36+
37+
>>> selection_sort([0])
38+
[0]
39+
40+
>>> selection_sort([2, -3, 0, 5, -1])
41+
[-3, -1, 0, 2, 5]
42+
43+
>>> selection_sort([0, 5, 3, 2, 2]) == sorted([0, 5, 3, 2, 2])
44+
True
45+
46+
>>> selection_sort([-2, -5, -45]) == sorted([-2, -5, -45])
47+
True
1748
"""
1849

1950
length = len(collection)

0 commit comments

Comments
 (0)