Insertion Sort in C++

Simplest Program for insertion Sort in C++

How it works?

insertion sort in C++

 

A graphical example of insertion sort.

Source: Wikipedia

PROGRAM:

#include <iostream>
using namespace std;

int main()
{
int a[16], i, j, k, temp;
cout<<"enter the elementsn";
for (i = 0; i < 5; i++)
{
cin>>a[i];
}
for (i = 1; i < 5; i++)
{
for (j = i; j >= 1; j--)
{
if (a[j] < a[j-1])
{
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
else
break;
}
}
cout<<"sorted arrayn"<<endl;
for (k = 0; k < 5; k++)
    cout<<a[k]<<endl;

}

 

Leave a Reply