Write a C++ program to sort array using insertion sort method.
Program Code:
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
Post A Comment:
0 comments: