C++ Online Compiler
Example: Simple Insertion Sort using Array in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Simple Insertion Sort using Array #include <iostream> // For input/output operations // Function to perform insertion sort on an array // arr[]: The array to be sorted // n: The size of the array void insertionSort(int arr[], int n) { // Loop through the array starting from the second element (index 1) // because the first element (index 0) is considered sorted by itself. for (int i = 1; i < n; i++) { int key = arr[i]; // Store the current element as 'key' to be inserted int j = i - 1; // Initialize 'j' to the last element of the sorted subarray (to the left of key) // Move elements of arr[0...i-1], that are greater than key, // to one position ahead of their current position. // This creates space for the 'key'. while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; // Shift element arr[j] to the right j = j - 1; // Move 'j' to the previous element in the sorted part } arr[j + 1] = key; // Place the 'key' in its correct sorted position } } // Function to print the elements of an 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: Declare and initialize an array int arr[] = {12, 11, 13, 5, 6}; // Calculate the size of the array int n = sizeof(arr) / sizeof(arr[0]); // Step 2: Print the original array to show its initial state std::cout << "Original array: "; printArray(arr, n); // Step 3: Call the insertionSort function to sort the array in ascending order insertionSort(arr, n); // Step 4: Print the sorted array to show the result std::cout << "Sorted array (ascending): "; printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS