Description: Selection sort is a simple comparison-based sorting algorithm that works by dividing the input list into two parts: a sorted part and an unsorted part. It repeatedly selects the smallest (or largest, depending on sorting order) element from the unsorted part and moves it to the end of the sorted part.
Here's a C++ implementation of selection sort:
#include <iostream>
using namespace std;
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i; // Assume the minimum is the first element of the unsorted part
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j; // Update minIndex if a smaller element is found
}
}
// Swap the found minimum element with the first element of the unsorted part
swap(arr[minIndex], arr[i]);
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
selectionSort function takes an array and its size as parameters.Selection sort is easy to understand and implement, making it a great educational tool. However, its time complexity makes it inefficient for large datasets. For practical applications, more efficient algorithms like quick sort or merge sort are preferred.
Open this section to load past papers