From 93f9bf0cdcf115bdb35e2a53bb3a53edae38d4e0 Mon Sep 17 00:00:00 2001 From: TDS Student <23f3003167@ds.study.iitm.ac.in> Date: Fri, 27 Mar 2026 08:40:01 +0530 Subject: [PATCH] Improve selection sort doctests and documentation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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. --- sorts/selection_sort.py | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/sorts/selection_sort.py b/sorts/selection_sort.py index 506836b53e44..a0261e9db030 100644 --- a/sorts/selection_sort.py +++ b/sorts/selection_sort.py @@ -2,8 +2,15 @@ def selection_sort(collection: list[int]) -> list[int]: """ Sorts a list in ascending order using the selection sort algorithm. - :param collection: A list of integers to be sorted. - :return: The sorted list. + Selection sort divides the input list into a sorted and unsorted region. + It repeatedly finds the minimum element from the unsorted region and + places it at the end of the sorted region. + + Time Complexity: O(n²) in all cases + Space Complexity: O(1) + + :param collection: A list of comparable items to be sorted. + :return: The same list sorted in ascending order. Examples: >>> selection_sort([0, 5, 3, 2, 2]) @@ -14,6 +21,30 @@ def selection_sort(collection: list[int]) -> list[int]: >>> selection_sort([-2, -5, -45]) [-45, -5, -2] + + >>> selection_sort([1]) + [1] + + >>> selection_sort([5, 4, 3, 2, 1]) + [1, 2, 3, 4, 5] + + >>> selection_sort([1, 2, 3, 4, 5]) + [1, 2, 3, 4, 5] + + >>> selection_sort([3, 3, 3, 3]) + [3, 3, 3, 3] + + >>> selection_sort([0]) + [0] + + >>> selection_sort([2, -3, 0, 5, -1]) + [-3, -1, 0, 2, 5] + + >>> selection_sort([0, 5, 3, 2, 2]) == sorted([0, 5, 3, 2, 2]) + True + + >>> selection_sort([-2, -5, -45]) == sorted([-2, -5, -45]) + True """ length = len(collection)