C++ Online Compiler
Example: Insertion Sort using Function in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Insertion Sort using Function #include <iostream> // For input/output operations // Function to perform Insertion Sort on an array void insertionSort(int arr[], int n) { // Step 1: Iterate from the second element (index 1) to the end of the array for (int i = 1; i < n; i++) { // Step 2: Store the current element to be inserted int key = arr[i]; // Step 3: Initialize j to the element just before the key 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 to compare with the next element } // Step 5: Place the key at its correct position in the sorted subarray arr[j + 1] = key; } } // 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; } int main() { // Step 1: Declare an unsorted integer array int arr[] = {12, 11, 13, 5, 6}; // Step 2: Calculate the size of the array int n = sizeof(arr) / sizeof(arr[0]); // Step 3: Print the original array std::cout << "Original array: "; printArray(arr, n); // Step 4: Call the insertionSort function to sort the array insertionSort(arr, n); // Step 5: Print the sorted array std::cout << "Sorted array: "; printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS