Pages

Monday, 20 September 2021

Insertion sort in c++

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
class insertionsort
{
 public:
 int a[33],i,j,n,temp;
 public:
 void getdata();
 void sort();
 void display();
};

void insertionsort::getdata()
{
 cout<<"Enter the size :"<<ends;
 cin>>n;
 for(i=0;i<n;i++)
  {
  cout<<"Enter the Element a["<<i<<"] :"<<ends;
  cin>>a[i];
  }
}

void insertionsort::sort()
{
  temp=0;
  for(j=0;j<n;j++)
    {
     temp=a[j];
     for(i=j-1;i>=0 && temp<a[i];i--)
       {
a[i+1]=a[i];
       }
      a[i+1]=temp;
      cout<<"\n pass"<<ends<<j+1<<ends<<"element inserted in proper place"<<ends<<temp<<endl;
      for(i=0;i<n;i++)
      {
      cout<<a[i]<<"  ";
      }
    }
}

void insertionsort::display()
 {
    cout<<"\n Sorted Array elements :";
    for(i=0;i<n;i++)
    {
     cout<<a[i]<<" ";
    }
    for(i=0;i<n;i++)
    {
     cout<<"\nAddress:"<< &a[i] <<"\tArray:"<<"a["<<i<<"]"<<"\tData:"<<a[i]<<"\tPosition or Location:"<<i+1;
    }
 }

void main()
{
 insertionsort is;
 clrscr();
 is.getdata();
 is.sort();
 is.display();
 getch();
}

output:


Insertion sort animation video link:
https://www.youtube.com/watch?v=JU767SDMDvA

No comments:

Post a Comment

Constructors & Destructors in c++

  Constructors :  A Constructor is a special member function, which is used to initialize the objects of its class. The Constructor is invok...