Insertion Sorting, Insertion sorting in C++, Insertion sorting example
Write a C++ program to sort array using insertion sort method. 

Program Code:
#include<iostream>
using namespace std;
int main()
{
int size, array[50];
int i, j, temp;

cout<<"Enter Array Size to sort : ";
cin>>size;
cout<<endl;
cout<<"Enter Array Elements one by one : ";
cout<<endl;
for(i=0; i<size; i++)
{
cin>>array[i];
}
cout<<"Sorting array using Insertion sort ... \n";
for(i=1; i<size; i++)
{
temp=array[i];
j=i-1;
while((temp<array[j]) && (j>=0))
{
array[j+1]=array[j];
j=j-1;
}
array[j+1]=temp;
}
cout<<"Array after sorting : ";
cout<<endl;
for(i=0; i<size; i++)
{
cout<<array[i]<<" ";
}
return 0;
}


The program code is tested on www.jdoodle.com

Output:
Enter Array Size to sort : 9
Enter Array Elements one by one : 
2 4 5 1 3 7 8 9 0
Sorting array using Insertion sort ............. 
Array after sorting : 
0 1 2 3 4 5 7 8 9 


Thanks
Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: