C++ Program for ShellSort Last Updated : 23 Jul, 2025 Comments Improve Suggest changes 3 Likes Like Report In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h'th element is sorted. CPP // C++ implementation of Shell Sort #include <iostream> /* function to sort arr using shellSort */ void shellSort(int arr[], int n) { // Start with a big gap, then reduce the gap for (int gap = n / 2; gap > 0; gap /= 2) { // Do a gapped insertion sort for this gap size. // The first gap elements arr[0..gap-1] are already in gapped order // keep adding one more element until the entire array is // gap sorted for (int i = gap; i < n; i += 1) { // add arr[i] to the elements that have been gap sorted // save arr[i] in temp and make a hole at position i int temp = arr[i]; // shift earlier gap-sorted elements up until the correct // location for arr[i] is found int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; // put temp (the original arr[i]) in its correct location arr[j] = temp; } } } void printArray(int arr[], int n) { for (int i = 0; i < n; i++) std::cout << arr[i] << " "; std::cout << "\n"; } int main() { int arr[] = { 12, 34, 54, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); std::cout << "Array before sorting: \n"; printArray(arr, n); shellSort(arr, n); std::cout << "Array after sorting: \n"; printArray(arr, n); } Output:Array before sorting: 12 34 54 2 3 Array after sorting: 2 3 12 34 54 Time Complexity: O(n2)Auxiliary Space: O(1) Please refer complete article on ShellSort for more details! Create Quiz Comment K kartik Follow 3 Improve K kartik Follow 3 Improve Article Tags : Sorting C++ Programs DSA Explore DSA FundamentalsLogic Building Problems 2 min read Analysis of Algorithms 1 min read Data StructuresArray Data Structure 3 min read String in Data Structure 2 min read Hashing in Data Structure 2 min read Linked List Data Structure 3 min read Stack Data Structure 2 min read Queue Data Structure 2 min read Tree Data Structure 2 min read Graph Data Structure 3 min read Trie Data Structure 15+ min read AlgorithmsSearching Algorithms 2 min read Sorting Algorithms 3 min read Introduction to Recursion 15 min read Greedy Algorithms 3 min read Graph Algorithms 3 min read Dynamic Programming or DP 3 min read Bitwise Algorithms 4 min read AdvancedSegment Tree 2 min read Binary Indexed Tree or Fenwick Tree 15 min read Square Root (Sqrt) Decomposition Algorithm 15+ min read Binary Lifting 15+ min read Geometry 2 min read Interview PreparationInterview Corner 3 min read GfG160 3 min read Practice ProblemGeeksforGeeks Practice - Leading Online Coding Platform 1 min read Problem of The Day - Develop the Habit of Coding 5 min read Like