C++ Online Compiler
Example: Insertion Sort in Ascending Order in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Insertion Sort in Ascending Order #include <iostream> #include <vector> // Using vector for dynamic array, but can be done with raw array void insertionSort(std::vector<int>& arr) { // Step 1: Iterate through the array starting from the second element // The first element (index 0) is considered already sorted by itself for (int i = 1; i < arr.size(); ++i) { // Step 2: Store the current element to be inserted int key = arr[i]; // Step 3: Initialize 'j' to the index of the last element in the sorted part int j = i - 1; // Step 4: Move elements of arr[0...i-1], that are greater than key, // to one position ahead of their current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; // Shift element to the right j = j - 1; // Move to the left in the sorted part } // Step 5: Place the key element at its correct position arr[j + 1] = key; } } int main() { // Step 1: Define an unsorted array std::vector<int> numbers = {12, 11, 13, 5, 6}; std::cout << "Original array: "; for (int num : numbers) { std::cout << num << " "; } std::cout << std::endl; // Step 2: Call the insertion sort function insertionSort(numbers); // Step 3: Print the sorted array std::cout << "Sorted array (ascending): "; for (int num : numbers) { std::cout << num << " "; } std::cout << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS