
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Implement Shell Sort
The shell sorting technique is based on the insertion sort. In the insertion sort, sometimes we need to shift a large block to insert an item in the correct position. In shell sort, we avoid large number of shifting. The sorting is done with specific interval. After each pass, the interval is reduced to make smaller interval. We call also say we use gapped insertion sort in shell sort as we compare elements separated by a gap.
In this article, we have an unsorted array. Our task is to sort the given unsorted array by implementing the shell sort in C++.
Example
The following example sorts the given unsorted array using the shell sort technique:
Input: arr = {23, 56, 97, 21, 35, 689, 854} Output: Sorted array: {21, 23, 35, 56, 97, 689, 854}
Steps to Implement Shell Sort
The following steps implement the shell sort technique:
- First, we calculate the initial gap using gap = n/2.
- Then we compare which are gap apart from each other. For example: suppose the gap is 3, then we compare the 0th element with 3rd, 1st element with 4th, and so on.
- If the element present after the gap i.e. arr[k + gap] is smaller than the element at the current position (arr[k]), then we swap both the elements otherwise we break the loop and compare next pair.
- We reduce the gap by half each time and keep repeating the process of comparing and swapping until the gap becomes 0. The inner loop implements a gapped insertion sort.
C++ Program to Implement Shell Sort
Here is the C++ code implementation of the shell sort using the above steps.
#include <iostream> #include <vector> using namespace std; void swapping(int &a, int &b) { int temp = a; a = b; b = temp; } void display(const vector<int> &array) { for (int num : array) cout << num << " "; cout << endl; } void shellSort(vector<int> &arr) { int n = arr.size(); for (int gap = n / 2; gap > 0; gap /= 2) { for (int j = gap; j < n; j++) { for (int k = j - gap; k >= 0; k -= gap) { if (arr[k + gap] >= arr[k]) break; else swapping(arr[k + gap], arr[k]); } } } } int main() { vector<int> arr = {29, 10, 14, 37, 13}; cout << "Array before Sorting: "; display(arr); shellSort(arr); cout << "Array after Sorting: "; display(arr); return 0; }
The output of the above code is given below:
Array before Sorting: 29 10 14 37 13 Array after Sorting: 10 13 14 29 37
Complexity of Shell Sorting Algorithm
- Time Complexity: The time complexity of the shell sort algorithm is O(n log n).
- Space Complexity: The space complexity of the shell sort algorithm is O(1).