C++ Online Compiler
Example: Insertion Sort without Function in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Insertion Sort without Function #include <iostream> #include <vector> // Using vector for dynamic array, can also use fixed-size array using namespace std; int main() { // Step 1: Initialize an array of integers vector<int> arr = {12, 11, 13, 5, 6}; int n = arr.size(); cout << "Original array: "; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; // Step 2: Implement the Insertion Sort algorithm // Outer loop iterates from the second element (index 1) to the end of the array for (int i = 1; i < n; i++) { int key = arr[i]; // Store the current element to be inserted int j = i - 1; // Initialize j to the last element of the sorted subarray // Inner loop: 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 subarray } arr[j + 1] = key; // Place the key in its correct position } // Step 3: Print the sorted array cout << "Sorted array: "; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; return 0; }
Output
Clear
ADVERTISEMENTS