Wednesday, 11 November 2026

Insertion Sort in Cpp



#include <iostream>

using namespace std;


int main()

{

    int a[5], i, j, temp;


    cout << "Enter 5 numbers: ";


    for(i = 0; i < 5; i++)

    {

        cin >> a[i];

    }


    for(i = 1; i < 5; i++)//Starts comparing from the second element. 

    {

        for(j = i; j > 0; j--)//- Compares the current element with the previous element. 

        {

            if(a[j] < a[j-1])- //Checks whether the current number is smaller than the previous number. 

            {

                temp = a[j];  //Swaps the two numbers. 

                a[j] = a[j-1];

                a[j-1] = temp;

            }

        }

    }


    cout << "Sorted array: ";


    for(i = 0; i < 5; i++)

    {

        cout << a[i] << " ";

    }


    return 0;

}