Insertion Sort
Loading editor...
#include <bits/stdc++.h>
using namespace std;
// Insertion sort that operates on a copy of the input vector
void insertionSort(vector<int> &array) {
int n = static_cast<int>(array.size()); // Length of the vector
// Start from the second element (index 1) – the sub‑array [0..i‑1] is already sorted
for (int i = 1; i < n; ++i) {
int key = array[i]; // Element to be inserted into the sorted part
int j = i - 1;
// Shift elements of the sorted sub‑array that are larger than `key` one position to the right
while (j >= 0 && array[j] > key) {
array[j + 1] = array[j];
--j;
}
// Place `key` into its correct position
array[j + 1] = key;
}
}
List of numbers to sort, space-separated.