Simple implementation or simulation of shell sort algorithm in c++ programming language

This tutorial give the idea about the shell sort and its implementation in c++ programming language. Shell sort is an in-place comparison sort. Means that the it sort the data by using comparison and exchanging of data.Shell sort is use the multi pass to sort the data. Time complexity of shell sort is can’t defined because of the time complexity of shell sort is depend upon the gape between elements. Shell sort is a simple extension of Insertion sort because of the in shell sort each pass is sorted by using insertion sort.

Coding:-

/* by www.computersciencearticle.in */
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
void DataEntryFunction(int array[10],int number)
{ 
cout<<"Enter the array elements for shell shortn"; 
for(int i=0;i<number;i++)  
{  
cout<<"Enter "<<i<<"th element n"; 
cin>>array[i];  
}
}
void displayFunction(int array[10],int number)
{ 
for(int i=0;i<number;i++)  
cout<<array[i]<<"t";
}
void shellsortMethod(int array[10],int number)
{ 
int MidVar=number/2; 
do 
{  
int swapVar;  
do
 {   
swapVar=0;   
for(int i=0;i<number-MidVar;i++)    
if(array[i]>array[i MidVar])    
{     
int t=array[i];
array[i]=array[i MidVar];
array[i MidVar]=t;
swapVar=1;    
}  
}  
while(swapVar); 
} 
while(MidVar=MidVar/2);
}
void main()
{ 
int array[100]; 
int number; 
clrscr(); 
cout<<"enter the number of element or size of arrayn"; 
cin>>number; 
DataEntryFunction(array,number);
cout<<"The array before shell sorting is n"; 
displayFunction(array,number); 
shellsortMethod(array,number); 
cout<<"nArray after shell sorting isn"; 
displayFunction(array,number); 
getch();}

Source Code: shell sort

Output:-
Let’s take array of 5 elements and want to sort using shell sort.
Array elements is 6, 1, 22, 4, 3
The output of shell sort is

Output of Shell sort algorithm to sort array element
One Response
  1. April 12, 2012