Introduction
Selection Sort is a simple comparison-based sorting algorithm.
The idea is:
- repeatedly find the minimum element
from the unsorted portion - place it at the correct position
After every pass:
- one element gets fixed permanently
This problem helps in understanding:
- sorting fundamentals
- minimum element selection
- swapping logic
- in-place sorting
Example
Input:arr = [64, 25, 12, 22, 11]
Output:
[11, 12, 22, 25, 64]
Explanation:
Smallest element is selected and moved to correct position during every pass.
Constraints
1 <= arr.length <= 10^5-10^4 <= arr[i] <= 10^4Approach 1 : Basic Selection Sort
Explanation
The simplest way to sort using Selection Sort is:
- Find smallest element
from unsorted portion - Swap it with current index
- Repeat for remaining elements
After every pass:
- left portion becomes sorted
Steps
- Traverse array.
- Find minimum element.
- Swap with current position.
- Continue remaining passes.
- Return sorted array.
Dry Run
Input:[64, 25, 12, 22, 11]
Pass 1: Minimum element:
11
Swap with 64
Array becomes: [11, 25, 12, 22, 64]
Pass 2:
Minimum element: 12
Swap with 25
Array becomes: [11, 12, 25, 22, 64]
Continue remaining passes...
Final Result: [11, 12, 22, 25, 64]
Basic Selection Sort Code
Complexity Analysis
Time Complexity: O(n²)Explanation:Minimum element is searched during every pass.
Space Complexity: O(1) Explanation:
Sorting is performed in-place.
Approach 2 : Optimized Selection Sort
Explanation
Selection Sort already performs:
- minimum possible swaps
Optimization idea:
- avoid unnecessary swapping
when minimum element
is already at correct position
This reduces redundant operations.
Steps
- Traverse array.
- Find minimum element.
- Check if swap is needed.
- Swap only if required.
- Return sorted array.
Dry Run
Input:[11, 12, 22, 25]
Pass 1: Minimum element already:
11
No swap needed
Pass 2: Minimum element already: 12 No swap needed Array already sorted
Final Result: [11, 12, 22, 25]
Optimized Selection Sort Code
Complexity Analysis
Best Case Time Complexity: O(n²)Average Case Time Complexity: O(n²)
Worst Case Time Complexity: O(n²)
Explanation:
Minimum searching is always required.
Space Complexity: O(1)
Explanation:
Sorting is performed in-place.
Edge Cases