Selection Sort in C++
1. What Is Selection Sort?
Selection Sort is a sorting algorithm that divides an array into two parts:
- Sorted portion: The part containing elements already placed in their correct positions.
- Unsorted portion: The part from which the smallest element is selected.
During every pass, the algorithm finds the smallest element in the unsorted portion and swaps it with the first element of that portion.
This process continues until the entire array becomes sorted.
Example
Consider the following unsorted array:
arr = {64, 25, 12, 22, 11}
Selection Sort finds the smallest element, 11, and places it at index 0. It then finds the next smallest element and places it at index 1.
After sorting:
arr = {11, 12, 22, 25, 64}
2. How Does Selection Sort Work?
Selection Sort repeatedly searches the unsorted portion of the array to find its minimum element.
- Start from the first index of the array.
- Assume the current index contains the smallest element.
- Compare it with every remaining element in the unsorted portion.
- Update the minimum index whenever a smaller element is found.
- After completing the search, swap the minimum element with the current element.
- Move to the next index and repeat the process.
- Continue until the array is sorted.
3. Understanding Selection Sort Step by Step
Consider this array:
arr = {64, 25, 12, 22, 11}
Pass 1
The first element, 64, is initially considered the minimum. We search the entire array to find the actual smallest element.
| Element Compared | Current Minimum | Action |
|---|---|---|
| 64 | 64 | Initial minimum |
| 25 | 25 | Update minimum |
| 12 | 12 | Update minimum |
| 22 | 12 | No change |
| 11 | 11 | Update minimum |
The smallest element is 11. Swap it with the first element, 64.
{11, 25, 12, 22, 64}
Pass 2
The first element is already sorted. Now search for the smallest element from index 1 to the end.
The smallest element in {25, 12, 22, 64} is 12. Swap 12 with 25.
{11, 12, 25, 22, 64}
Pass 3
Search the remaining unsorted portion:
{25, 22, 64}
The smallest element is 22. Swap it with 25.
{11, 12, 22, 25, 64}
Pass 4
The remaining unsorted portion is:
{25, 64}
The smallest element is already at the correct position, so no swap is needed.
{11, 12, 22, 25, 64}
Final Sorted Array: 11 12 22 25 64
4. Selection Sort Algorithm
The basic algorithm follows these steps:
- Run an outer loop from index 0 to n - 2.
- Set minIndex equal to the current index.
- Run an inner loop from the next index to n - 1.
- Compare each element with the current minimum element.
- If a smaller element is found, update minIndex.
- After the inner loop finishes, swap arr[i] with arr[minIndex].
- Repeat until the array is sorted.
Pseudocode
SelectionSort(arr, n):
for i = 0 to n - 2:
minIndex = i
for j = i + 1 to n - 1:
if arr[j] < arr[minIndex]:
minIndex = j
swap(arr[i], arr[minIndex])
5. C++ Code: Selection Sort
The following program implements Selection Sort using two nested loops. The outer loop selects the position to fill, while the inner loop finds the smallest element in the remaining unsorted portion.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void selectionSort(vector<int>& arr) {
int n = arr.size();
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
swap(arr[i], arr[minIndex]);
}
}
int main() {
vector<int> arr = {64, 25, 12, 22, 11};
selectionSort(arr);
cout << "Sorted Array: ";
for (int x : arr) {
cout << x << " ";
}
return 0;
}
Output
Sorted Array: 11 12 22 25 64
6. Understanding the Nested Loops
Selection Sort uses two loops to find the minimum element and place it in the correct position.
Outer Loop
for (int i = 0; i < n - 1; i++)
The outer loop represents the current position where the smallest remaining element should be placed.
It runs from index 0 to n - 2 because when the first n - 1 positions are correctly filled, the last element is automatically in its correct position.
Minimum Index
int minIndex = i;
At the beginning of each pass, we assume the current element is the smallest element in the unsorted portion.
Inner Loop
for (int j = i + 1; j < n; j++)
The inner loop checks every element after the current index to find the smallest element.
Updating the Minimum Index
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
Whenever a smaller element is found, its index becomes the new minIndex.
Swapping
swap(arr[i], arr[minIndex]);
After the inner loop finishes, the minimum element is placed at the current position.
7. Complete Dry Run of Selection Sort
Consider the following array:
arr = {29, 10, 14, 37, 13}
| Pass | Unsorted Portion | Smallest Element | Swap | Array After Pass |
|---|---|---|---|---|
| 1 | 29, 10, 14, 37, 13 | 10 | 29 and 10 | 10, 29, 14, 37, 13 |
| 2 | 29, 14, 37, 13 | 13 | 29 and 13 | 10, 13, 14, 37, 29 |
| 3 | 14, 37, 29 | 14 | No change | 10, 13, 14, 37, 29 |
| 4 | 37, 29 | 29 | 37 and 29 | 10, 13, 14, 29, 37 |
Final Sorted Array: 10 13 14 29 37
8. Selection Sort in Descending Order
Selection Sort can also arrange elements in descending order. Instead of finding the smallest element, we find the largest element in the unsorted portion.
For ascending order, we use:
if (arr[j] < arr[maxIndex])
For descending order, we use:
if (arr[j] > arr[maxIndex])
C++ Code: Descending Selection Sort
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void selectionSortDescending(vector<int>& arr) {
int n = arr.size();
for (int i = 0; i < n - 1; i++) {
int maxIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] > arr[maxIndex]) {
maxIndex = j;
}
}
swap(arr[i], arr[maxIndex]);
}
}
int main() {
vector<int> arr = {64, 25, 12, 22, 11};
selectionSortDescending(arr);
cout << "Descending Array: ";
for (int x : arr) {
cout << x << " ";
}
return 0;
}
Output
Descending Array: 64 25 22 12 11
9. Selection Sort with Minimum Swaps
One useful property of Selection Sort is that it performs at most one swap during each pass.
We can avoid unnecessary self-swapping by checking whether the minimum element is already at the current position.
C++ Code
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void selectionSort(vector<int>& arr) {
int n = arr.size();
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap only when the minimum is elsewhere
if (minIndex != i) {
swap(arr[i], arr[minIndex]);
}
}
}
int main() {
vector<int> arr = {5, 2, 4, 1, 3};
selectionSort(arr);
cout << "Sorted Array: ";
for (int x : arr) {
cout << x << " ";
}
return 0;
}
Output
Sorted Array: 1 2 3 4 5
10. Time Complexity of Selection Sort
Selection Sort searches the entire unsorted portion during every pass. Therefore, the number of comparisons remains almost the same regardless of the initial arrangement of the elements.
Best Case
The best case occurs when the array is already sorted. Even then, Selection Sort checks the remaining elements to confirm that the current element is the smallest.
Best Case: O(n²)
Average Case
In the average case, the elements are arranged in an arbitrary order. The algorithm still searches the entire unsorted portion during each pass.
Average Case: O(n²)
Worst Case
The worst case also requires the algorithm to compare every element in the unsorted portion during each pass.
Worst Case: O(n²)
Number of Comparisons
For an array of n elements, the number of comparisons is:
(n - 1) + (n - 2) + ... + 2 + 1
= n(n - 1) / 2
Therefore, the total number of comparisons grows quadratically.
11. Space Complexity of Selection Sort
Selection Sort performs sorting directly in the original array. It does not require an additional array or another data structure.
It uses only a few variables, such as i, j, and minIndex.
Auxiliary Space Complexity: O(1)
12. Complexity Summary
| Case or Operation | Complexity |
|---|---|
| Best Case Time | O(n²) |
| Average Case Time | O(n²) |
| Worst Case Time | O(n²) |
| Auxiliary Space | O(1) |
| Maximum Swaps | At most n - 1 |
| Comparisons | n(n - 1) / 2 |
13. Properties of Selection Sort
| Property | Description |
|---|---|
| Algorithm Type | Comparison-based sorting |
| Sorting Method | Selecting the minimum element |
| In-place | Yes |
| Stable | No, in the standard swap-based implementation |
| Adaptive | No |
| Best Case | O(n²) |
| Worst Case | O(n²) |
| Auxiliary Space | O(1) |
Is Selection Sort Stable?
The standard swap-based Selection Sort is not stable. A swap can change the relative order of two elements having equal values.
Example of Instability
Suppose we have the following records. The letters identify different records that have the same value.
{4A, 4B, 3}
During the first pass, Selection Sort selects 3 and swaps it with 4A.
{3, 4B, 4A}
The original order of the equal elements 4A and 4B has changed. This demonstrates why standard Selection Sort is not stable.
Is Selection Sort In-place?
Yes. Selection Sort modifies the original array and uses only a constant amount of extra memory. Therefore, it is an in-place sorting algorithm.
14. Selection Sort vs Bubble Sort
Both algorithms are simple comparison-based sorting techniques, but they use different methods to arrange elements.
| Feature | Selection Sort | Bubble Sort |
|---|---|---|
| Basic Operation | Select minimum element | Compare adjacent elements |
| Element Movement | Minimum moves to the front | Maximum moves toward the end |
| Best Case | O(n²) | O(n) when optimized |
| Average Case | O(n²) | O(n²) |
| Worst Case | O(n²) | O(n²) |
| Swaps | At most n - 1 | Can be O(n²) |
| Stable | No, in the standard implementation | Yes, with strict adjacent comparisons |
| Auxiliary Space | O(1) | O(1) |
15. Advantages of Selection Sort
- Easy to understand and implement.
- Requires only O(1) auxiliary space.
- Performs at most n - 1 swaps in the standard implementation.
- Useful when minimizing the number of writes or swaps is important.
- Works without requiring the input array to be partially or fully sorted.
16. Disadvantages of Selection Sort
- Best, average, and worst-case time complexity are all O(n²).
- It does not become faster when the input array is already sorted.
- The standard implementation is not stable.
- It is not suitable for large datasets.
- More efficient sorting algorithms are available for general-purpose sorting.
17. Common Mistakes
- Not resetting minIndex: Initialize minIndex = i at the beginning of every outer-loop pass.
- Using the wrong comparison: For ascending order, use arr[j] < arr[minIndex].
- Swapping inside the inner loop: Complete the search for the minimum element before performing the swap.
- Incorrect inner loop starting point: Start j from i + 1 because the current element is already the initial minimum.
- Incorrect outer loop boundary: The outer loop only needs to run until n - 2.
- Assuming it is stable: The standard swap-based implementation can change the relative order of equal elements.
- Assuming the best case is O(n): Selection Sort still checks the remaining unsorted elements even when the array is sorted.
18. Applications of Selection Sort
- Learning basic comparison-based sorting algorithms.
- Sorting small collections of elements.
- Situations where minimizing the number of swaps is important.
- Understanding minimum selection and array manipulation.
- Educational demonstrations of sorting and algorithm analysis.
19. Interview Questions
- What is Selection Sort?
- How does Selection Sort work?
- What is the role of minIndex?
- What is the time complexity of Selection Sort?
- Why is the best-case time complexity also O(n²)?
- What is the auxiliary space complexity of Selection Sort?
- Is Selection Sort stable? Explain with an example.
- Is Selection Sort an in-place sorting algorithm?
- How many swaps can Selection Sort perform at most?
- What is the total number of comparisons performed by Selection Sort?
- What is the difference between Selection Sort and Bubble Sort?
- How can Selection Sort be modified to sort in descending order?
- Why is Selection Sort not adaptive?
- When would Selection Sort be preferred over another simple sorting algorithm?
20. Practice Problems
Problem 1: Sort an Array Using Selection Sort
Given an array of integers, sort the elements in ascending order using Selection Sort.
Input:
{64, 25, 12, 22, 11}
Output:
{11, 12, 22, 25, 64}
Problem 2: Sort an Array in Descending Order
Modify Selection Sort to arrange the elements from largest to smallest.
Input:
{5, 3, 8, 4, 2}
Output:
{8, 5, 4, 3, 2}
Problem 3: Count the Number of Swaps
Modify Selection Sort to count the number of actual swaps performed. Do not count a swap when the minimum element is already at the current position.
Input:
{4, 3, 2, 1}
Output:
2
Problem 4: Find the Kth Smallest Element
Use the Selection Sort idea to find the kth smallest element in an array. You do not need to sort the entire array if only the first k positions are required.
Input:
arr = {7, 10, 4, 3, 20, 15}
k = 3
Output:
7
Problem 5: Sort an Already Sorted Array
Apply Selection Sort to an already sorted array and count the number of comparisons.
Input:
{1, 2, 3, 4, 5}
Output:
Sorted Array: {1, 2, 3, 4, 5}
Comparisons: 10
21. Summary
- Selection Sort is a comparison-based sorting algorithm.
- It repeatedly selects the smallest element from the unsorted portion.
- The selected minimum element is swapped with the first unsorted element.
- It divides the array into sorted and unsorted portions.
- Its best, average, and worst-case time complexities are O(n²).
- Its auxiliary space complexity is O(1).
- It performs at most n - 1 swaps in the standard implementation.
- Standard Selection Sort is in-place but not stable.