Selection Sort is a simple comparison-based sorting algorithm that repeatedly selects the smallest (or largest) element from the unsorted portion and places it in its correct position. This process continues for multiple passes until the entire array is sorted, with the sorted section growing incrementally. While easy to implement, Selection Sort is inefficient for large datasets due to its
𝑂(𝑛2) time complexity.
Selection Sort uses several passes through the array to sort it. In each pass, the smallest (or largest) unsorted element is selected and placed in its correct position in the sorted section.
Unlike Bubble Sort, Selection Sort does not have an early termination condition. It always makes 𝑛−1 passes, even if the array becomes sorted before the final pass.
// selectionsort.cpp#include <iostream>#include <vector>using namespace std;void selectionSort(vector<int> &v){ int n = v.size(); for (int i = 0; i < n - 1; i++) { int min_idx = i; for (int j = i + 1; j < n; j++) { if (v[j] < v[min_idx]) { min_idx = j; } } if (i != min_idx) { swap(v[i], v[min_idx]); } }}int main(){ vector<int> arr{9, 5, 4, 1}; selectionSort(arr); for (int &ele : arr) { cout << ele << " "; }}
# selection_sort.pydef selection_sort(arr): n = len(arr) for i in range(n-1): min_idx = i for j in range(i+1, n): if arr[j] < arr[min_idx]: min_idx = j if i != min_idx: arr[i], arr[min_idx] = arr[min_idx], arr[i] return arr# Example usagearr = [9, 5, 4, 1]selection_sort(arr)print(arr)
// selectionSort.jsfunction selectionSort(arr) { const n = arr.length; for (let i = 0; i < n - 1; i++) { let min_idx = i; for (let j = i + 1; j < n; j++) { if (arr[j] < arr[min_idx]) { min_idx = j; } } if (i !== min_idx) { [arr[i], arr[min_idx]] = [arr[min_idx], arr[i]]; } } return arr;}// Example usageconst arr = [9, 5, 4, 1];selectionSort(arr);console.log(arr);