C++ Program: Insertion Sort
// 4 Write a C++ program to sort the element of an array in ascending order using insertion sort.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class Sort
{
private:
int a[10], n, i;
public:
void readdata( );
void insertionsort( );
void display( );
};
void Sort::readdata( )
{
cout<<"Enter the size of the array:"<<endl;
cin>>n;
cout<<"Enter the elements for the array:"<<endl;
for(i=0; i<n; i++)
cin>>a[i];
}
void Sort::insertionsort( )
{
int j, temp;
for(i=1; i<n; i++)
{
j = i;
while(j >= 1)
{
if(a[j] < a[j-1])
{
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
j = j-1;
}
}
}
void Sort::display( )
{
for(i=0; i<n; i++)
cout<<a[i]<<"\t";
cout<<endl;
}
void main( )
{
Sort s;
clrscr();
s.readdata( );
cout<<"Unsorted List......"<<endl;
cout<<"*******************"<<endl;
s.display( );
s.insertionsort( );
cout<<"Sorted List........"<<endl;
cout<<"*******************"<<endl;
s.display( );
getch( );
}
Comments
Post a Comment