Selection Sort
v
S
D
A
O
A
R
P
from collections.abc import MutableSequence
from typing import Any, Protocol
class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...
def selection_sort[T: Comparable](collection: MutableSequence[T]) -> MutableSequence[T]:
"""
Sorts a list in ascending order using the selection sort algorithm.
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 mutable sequence of comparable items to be sorted.
:return: The same sequence sorted in ascending order.
Time Complexity: O(n^2) - Due to the nested loops, where n is the length
of the collection. The outer loop runs n-1 times, and the inner loop
runs n-i-1 times for each iteration.
Space Complexity: O(1) - Only a constant amount of extra space is used
for variables (length, i, min_index, k).
Examples:
>>> selection_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> selection_sort([])
[]
>>> 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
>>> selection_sort(["d", "a", "c", "b"])
['a', 'b', 'c', 'd']
>>> selection_sort([3.2, 1.1, 2.4, 0.5])
[0.5, 1.1, 2.4, 3.2]
"""
length = len(collection)
for i in range(length - 1):
min_index = i
for k in range(i + 1, length):
if collection[k] < collection[min_index]:
min_index = k
if min_index != i:
collection[i], collection[min_index] = collection[min_index], collection[i]
return collection
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
sorted_list = selection_sort(unsorted)
print("Sorted List:", sorted_list)
About this Algorithm
Problem Statement
Given an unsorted array of n elements, write a function to sort the array
Approach
- select the smallest element from the array
- put it at the beginning of the array
- then select the smallest array from the remaining unsorted list
- append it to the sorted array at the beginning
- keep doing this for every element of the array
- repeat the above process n times
Time Complexity
O(n^2) Worst case performance
O(n^2) Best-case performance
O(n^2) Average performance
Space Complexity
O(1) Worst case
Example
arr[] = {80, 10, 40, 30}
Indexes: 0 1 2 3
1. Index = 0
Select the minimum number from the array (between index 0-3), ie, 10
2. Swap 10 and 80 (arr[0])
3. The array now is {10, 80, 40, 30}
4. Index = 1
Select the minimum number from the array (between index 1-3), ie, 30
5. Swap 30 and 80 (arr[1])
6. The array now is {10, 30, 40, 80}
7. Index = 2
Select the minimum number from the array (between index 2-3), ie, 40
8. Swap 40 and 40 (arr[2])
9. The array now is {10, 30, 40, 80}
The array is now sorted.
Video Explanation
A video explaining the Selection Sort Algorithm