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.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *