Q:

Implement shell sort using C++ program

0

Implement shell sort using C++ program

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Algorithm:

Step 1: Initialize the value of gap.

Step 2: Divide the list into smaller sub-lists of equal interval gap.

Step 3: Sort each sub-list using insertion sort.

Step 4: Repeat until the list is sorted.

Consider the given program:

#include<iostream>
using namespace std;

/*Method to sort the list/array*/
void shellSort(int sort[],int size)      
{
	for(int gap=size/2;gap>0;gap/=2)
	{
		for(int i=gap;i<size;i++)
		{
			int temp=sort[i];
			int j;
			for(j=i; j>=gap && sort[j-gap]>temp; j-=gap)
			{
				sort[j]=sort[j-gap];
			}
			sort[j]=temp;
		}
	}	
}

//main program
int main()
{
	int size;               

	cout<<"Enter the size of the array :";
	cin>>size;

	int sort[size];
	for(int i=0;i<size;i++)
	{
		cin>>sort[i];
	}

	shellSort(sort,size);

	cout<<"Array after sorting is :";
	for(int i=0;i<size;i++)
	{
		cout<<sort[i]<<" ";
	}

	cout<<endl;
	
	return 0;
}

Output

 
FIRST INPUT:
Enter the size of the array :6
87 15 34 99 56 44
Array after sorting is :15 34 44 56 87 99

SECOND INPUT :
Enter the size of the array :10
13 54 36 87 36 42 11 68 91 9
Array after sorting is :9 11 13 36 36 42 54 68 87 91

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now