πΉ 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
Case | Time Complexity |
---|---|
Best | O(nΒ²) |
Average | O(nΒ²) |
Worst | O(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.