Program for Shell Sort in C and C++

Here you will get the program for shell sort in C and C++.

Shell short is an improved and productive rendition of inclusion sort.

In this calculation, we sort the pair of components that are far separated by hole h. The procedure is rehashed by lessening h until it gets 1.

Program for Shell Sort in C

#include<stdio.h>
 
void sort(int a[],int n)
{
	int gap,i,j,temp;
	for(gap=n/2;gap>0;gap/=2)
	{
		for(i=gap;i<n;i+=1)
		{
			temp=a[i];
			
			for(j=i;j>=gap&&a[j-gap]>temp;j-=gap)
				a[j]=a[j-gap];
			
			a[j]=temp;
		}
	}
}
 
int main()
{
	int a[20],i,n;
	
	printf("Enter number of elements:");
	scanf("%d",&n);
		
	printf("Enter array elements:\n");
	for(i=0;i<n;++i)
		scanf("%d",&a[i]);
 
	sort(a,n);
 
	printf("\nArray after shell sort:\n");
	for(i=0;i<n;++i)
		printf("%d ",a[i]);
 
    return 0;
}

Program for Shell Sort in C++

#include<iostream>
 
using namespace std;
 
void sort(int a[],int n)
{
	int gap,i,j,temp;
 
	for(gap=n/2;gap>0;gap/=2)
	{
		for(i=gap;i<n;i+=1)
		{
			temp=a[i];
			for(j=i;j>=gap&&a[j-gap]>temp;j-=gap)
				a[j]=a[j-gap];
			
			a[j]=temp;
		}
    }
}
 
int main()
{
	int a[20],i,n;
	
	cout<<"Enter number of elements:";
	cin>>n;
		
	cout<<"Enter array elements:\n";
	for(i=0;i<n;++i)
		cin>>a[i];
 
	sort(a,n);
 
	cout<<"\nArray after shell sort:\n";
	for(i=0;i<n;++i)
		cout<<a[i]<<" ";
 
    return 0;
}

Output

Enter number of elements:5
Enter array elements:
56 7 2 9 12

Array after shell sort:
2 7 9 12 56

Video For Learning Self Sort

Leave a Comment

error: Alert: Content is protected!!