Selection Sort is a simple comparison-based sorting algorithm. It divides the array into two parts:
In each iteration, it selects the minimum element from the unsorted part and swaps it with the first unsorted element, growing the sorted section by one.
This method repeatedly selects the smallest remaining element — hence the name Selection Sort.
Case | Time Complexity |
---|---|
Best | O(n²) |
Average | O(n²) |
Worst | O(n²) |
#include <iostream>
using namespace std;
// Function to perform Selection Sort
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
// Find the index of the minimum element
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum with the first element
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
// Print the array after each pass
cout << "After pass " << i + 1 << ": ";
for (int k = 0; k < n; k++) {
cout << arr[k] << " ";
}
cout << endl;
}
}
// Utility function to print an array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
// Main function
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array:\n";
printArray(arr, n);
selectionSort(arr, n);
cout << "Sorted array:\n";
printArray(arr, n);
return 0;
}
Original array:
64 25 12 22 11
After pass 1: 11 25 12 22 64
After pass 2: 11 12 25 22 64
After pass 3: 11 12 22 25 64
After pass 4: 11 12 22 25 64
Sorted array:
11 12 22 25 64
We will sort:
[64, 25, 12, 22, 11]
[11, 25, 12, 22, 64]
[11, 12, 25, 22, 64]
[11, 12, 22, 25, 64]
[11, 12, 22, 25, 64]
[11, 12, 22, 25, 64]