Selection Sort Algorithm in Python

๐Ÿ”น Introduction

Selection Sort is a simple comparison-based sorting algorithm. It divides the input list into a sorted and an unsorted part and repeatedly selects the smallest (or largest) element from the unsorted part and moves it to the sorted part.


๐Ÿ”ง Python Code

pythonCopyEditdef selection_sort(arr):
    n = len(arr)
    for i in range(n):
        min_idx = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr

# Example usage
numbers = [64, 25, 12, 22, 11]
print("Sorted array:", selection_sort(numbers))

๐Ÿ” Example

Input: [64, 25, 12, 22, 11]
Output: [11, 12, 22, 25, 64]


๐Ÿ“Š Time & Space Complexity

CaseTime Complexity
BestO(nยฒ)
AverageO(nยฒ)
WorstO(nยฒ)
  • Space Complexity: O(1) (in-place sorting)

๐Ÿ“– Explanation

Selection Sort works by finding the minimum element in each iteration and placing it in the correct position. Itโ€™s intuitive but inefficient for large lists.

Unlike bubble sort, it minimizes the number of swaps โ€” this can be advantageous when memory write is a costly operation.


๐ŸŒ Real-World Usage

Though not used in production systems due to poor time complexity, selection sort is helpful in:

  • Educational settings
  • Environments where memory writes are limited
  • Sorting very small datasets

๐Ÿ Final Thoughts

Selection Sort is a great way to understand the fundamentals of sorting. While inefficient for large datasets, it’s still a valuable educational tool.