Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
// Program to implement Shell sort


#include<iostream.h>
#include<iomanip.h>

class shellsort
{
     private:
          int *x;
          int items;
     public:
          shellsort(int);
          ~shellsort();
          void input(int [ ]);
          void display();
          void sort();
};

shellsort::shellsort(int n)
{
     items=n;
     x=new int[items];
}


shellsort::~shellsort()
{
     delete [ ] x;
}


void shellsort::input(int a[ ])
{
     for(int i=0;i<items;i++)
     x[i]=a[i];
}


void shellsort::display()
{
     cout<<"\n Sorted elements are :";
     for(int i=0;i<items;i++)
     cout<<setw(3)<<x[i];
}


void shellsort::sort()
{
     int temp,i,h;
     for(h=1;h<items/9;h=3*h+1);
     for(;h>0;h /=3)
     {
          for(i=h;i<items;i++)
          {

               int j;
               temp=x[i];
               for(j=i-h;j>=0;j -=h)
               {
                    if(temp<x[j])
                    x[j+h]=x[j];
                    else
                    break;
               }
               x[j+h]=temp;
          }
     }
}


int main()
{
     int elements[100],n;
     cout<<"Enter how many elements \n";
     cin>>n;
     cout<<"Enter"<<n<<"elements \n";
     for(int i=0;i<n;i++)
     cin>>elements[i];
     shellsort obj(n);
     obj.input(elements);
     obj.sort();
     obj.display();
     return 0;
}


Test data

Enter how many elements
6
Enter 6 elements
90  12  68  22  11  54

Output
Sorted elements are : 11  12  22  54  68  90