Overview
Selection Sort is an in-place comparison sorting algorithm that divides the input list into two parts: a sorted portion at the left end and an unsorted portion at the right end. Initially, the sorted portion is empty and the unsorted portion is the entire list. The algorithm proceeds by finding the smallest element in the unsorted portion and swapping it with the leftmost unsorted element.Implementation
How It Works
- Find Minimum: Search the unsorted portion for the minimum element
- Swap: Swap the minimum element with the first element of the unsorted portion
- Expand Sorted Region: Move the boundary between sorted and unsorted portions one element to the right
- Repeat: Continue until the entire array is sorted
Selection Sort performs exactly n-1 swaps, which can be advantageous when write operations are expensive.
Complexity Analysis
Time Complexity
- Best Case: O(n²) - always scans entire unsorted portion
- Average Case: O(n²)
- Worst Case: O(n²)
Space Complexity
- Space: O(1) - sorts in place
- Auxiliary: O(1) - only uses a few variables
Usage Example
Visual Example
Let’s trace through sorting[64, 25, 12, 22, 11]:
Characteristics
Stability
Stability
Selection Sort is not stable by default. Equal elements may not maintain their relative order. However, it can be made stable with modifications.
In-Place
In-Place
Yes, Selection Sort is in-place. It requires only O(1) additional memory.
Adaptive
Adaptive
No, Selection Sort is not adaptive. It always performs O(n²) comparisons regardless of initial order.
Online
Online
No, Selection Sort is not online. It needs access to all elements before sorting.
When to Use
Good for:- Very small datasets where simplicity matters
- Situations where write operations are expensive (only n-1 swaps)
- Memory-constrained environments (O(1) space)
- Educational purposes to understand sorting fundamentals
- Working with large datasets
- Performance is critical
- You need a stable sort
- Input data might be partially sorted (no benefit unlike Insertion Sort)
Unique Characteristics
Minimal Swaps: Selection Sort makes at most n-1 swaps, which is optimal. This makes it useful when writing to memory is significantly more expensive than reading.
Number of Operations
For an array of size n:- Comparisons: Always (n-1) + (n-2) + … + 1 = n(n-1)/2 ≈ n²/2
- Swaps: At most n-1 (one per pass)
- Memory Reads: Approximately n² (from comparisons)
- Memory Writes: At most 3(n-1) (from swaps)
Comparison with Other Sorts
| Algorithm | Best Case | Average Case | Worst Case | Space | Stable | Swaps |
|---|---|---|---|---|---|---|
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | No | n-1 |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes | O(n²) |
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes | O(n²) |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No | O(n log n) |
Code Walkthrough
The implementation consists of two functions:Helper Function: min()
start.