Quantcast
Channel: The Crazy Programmer
Viewing all articles
Browse latest Browse all 761

Program for Shell Sort in C and C++

$
0
0

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

Shell short is an improved and efficient version of insertion sort.

In this algorithm we sort the pair of elements that are far apart by gap h. The process is repeated by reducing h until it becomes 1.

Program for Shell Sort in C and C++

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

 

You can watch below video to learn more about shell sort.

The post Program for Shell Sort in C and C++ appeared first on The Crazy Programmer.


Viewing all articles
Browse latest Browse all 761

Trending Articles