Selection Sort in C++
Selection Sort Algorithm in C++ (Complete Implementation).
1#include <iostream>2using namespace std;34void selectionSort(int arr[], int n) {5 for (int i = 0; i < n - 1; i++) {6 int minIndex = i;78 // Find minimum element in unsorted portion9 for (int j = i + 1; j < n; j++) {10 if (arr[j] < arr[minIndex]) {11 minIndex = j;12 }13 }1415 // Swap found minimum with first element16 if (minIndex != i) {17 swap(arr[i], arr[minIndex]);18 }19 }20}2122void printArray(int arr[], int n) {23 for (int i = 0; i < n; i++) {24 cout << arr[i] << " ";25 }26 cout << endl;27}2829int main() {30 int arr[] = {64, 34, 25, 12, 22, 11, 90};31 int n = sizeof(arr) / sizeof(arr[0]);3233 cout << "Original array: ";34 printArray(arr, n);3536 selectionSort(arr, n);3738 cout << "Sorted array: ";39 printArray(arr, n);4041 return 0;42}
Output
Original array: 64 34 25 12 22 11 90 Sorted array: 11 12 22 25 34 64 90
What's going on
The program sorts an array of integers using the Selection Sort algorithm. For example:
Selection Sort divides the array into two parts: sorted (at the beginning) and unsorted (remaining elements). In each iteration, it finds the minimum from the unsorted part and adds it to the sorted part.
Header File Used
This header provides:
1#include <iostream>
Understanding Selection Sort
Algorithm Concept
:
Visual Example
:
Initial: [64, 34, 25, 12, 22, 11, 90]
|sorted| |------unsorted------|
Pass 1: Find min (11) → swap with 64
[11, 34, 25, 12, 22, 64, 90]
|sorted| |----unsorted----|
Pass 2: Find min (12) → swap with 34
[11, 12, 25, 34, 22, 64, 90]
|--sorted--| |--unsorted--|
Continue until all sorted...
Function: selectionSort()
void selectionSort(int arr[], int n) {
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;
}
}
if (minIndex != i) {
swap(arr[i], arr[minIndex]);
}
}
}
How it works
:
Step-by-Step Algorithm
Pass 1 (i=0)
:
Pass 2 (i=1)
:
Continue for n-1 passes...
Finding Minimum Element
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
How it works
:
Example
(finding min in [34, 25, 12, 22, 64, 90]):
Swap Operation
if (minIndex != i) {
swap(arr[i], arr[minIndex]);
}
How it works
:
Why Check minIndex != i?
:
Time and Space Complexity
Time Complexity
: O(n²) in all cases
Space Complexity
: O(1)
Stability
: Not Stable
When to Use Selection Sort
Best For
:
Not Recommended For
:
Important Considerations
Number of Passes
:
Comparison Count
:
Swap Count
:
return 0;
This ends the program successfully.