C++ Online Compiler
Example: C++ Insertion Sort Algorithm in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// C++ Insertion Sort Algorithm #include <iostream> // Function to print an array void printArray(int arr[], int n) { for (int i = 0; i < n; i++) { std::cout << arr[i] << " "; } std::cout << std::endl; } // Function to perform insertion sort void insertionSort(int arr[], int n) { // Iterate from the second element (index 1) to the end of the array for (int i = 1; i < n; i++) { // 'key' is the element to be inserted into the sorted subarray int key = arr[i]; // 'j' is the index of the last element in the sorted subarray int j = i - 1; // 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 subarray } // Place 'key' at its correct position in the sorted subarray arr[j + 1] = key; } } int main() { // Step 1: Define an unsorted array int arr[] = {12, 11, 13, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); // Step 2: Print the original array std::cout << "Original array: "; printArray(arr, n); // Step 3: Apply insertion sort insertionSort(arr, n); // Step 4: Print the sorted array std::cout << "Sorted array: "; printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS