C++ Online Compiler
Example: Insertion Sort in Array in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Insertion Sort in Array #include <iostream> #include <vector> // Using vector for dynamic array, but works with C-style arrays too // Function to perform insertion sort on an array void insertionSort(int arr[], int n) { // Start from the second element as the first element is considered sorted for (int i = 1; i < n; ++i) { int key = arr[i]; // The element to be inserted int j = i - 1; // Index of the last element in the sorted part // 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 previous element in the sorted part } arr[j + 1] = key; // Place the key in its correct position } } // Function to print the array void printArray(int arr[], int n) { for (int i = 0; i < n; ++i) { std::cout << arr[i] << " "; } std::cout << std::endl; } int main() { // Step 1: Define an array to be sorted int arr[] = {12, 11, 13, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); std::cout << "Original array: "; printArray(arr, n); // Step 2: Apply insertion sort insertionSort(arr, n); std::cout << "Sorted array: "; printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS