Insertion Sort

#include<iostream>
#include<conio.h>
#define max 50
using namespace std;
int main()
{
int a[max];
cout<<"How many elements you want to enter: ";
int num,v,j;
cin>>num;
cout<<"Enter Elements one by one: \n";
for(int i=0;i<num;i++)
cin>>a[i];
for(int i=0;i<num;i++)
{
v=a[i];
j=i-1;
while (j>=0 && a[j]>v)
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=v;
}
cout<<"List after Sorting: ";
for(int i=0;i<num;i++)
cout<<"  "<<a[i];
getch();
return 0;
}
Output:

How it work:-
89 | 45 68  90  29  34  17
45  89 | 68  90  29  34  17
45  68  89 | 90  29  34  17
45  68  89  90 | 29  34  17
29  45  68  89  90 | 34  17
29  34  45  68  89  90 | 17
17  29  34  45  68  89  90

Popular posts from this blog

Shutdown Pc

Ellipse using OpenGl

String Comparisons