ShellSort - GeeksforGeeks

17 Aug, 2021
ShellSort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of shellSort is to allow exchange of far items. 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.
Following is the implementation of ShellSort.
C++
Java
Python3
C#
Javascript
// C++ implementation of Shell Sort#include  <iostream>using namespace std; /* function to sort arr using shellSort */int 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 a[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 a[i] to the elements that have been gap sorted            // save a[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 a[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 a[i]) in its correct location            arr[j] = temp;        }    }    return 0;} void printArray(int arr[], int n){    for (int i=0; i<n; i++)        cout << arr[i] << " ";} int main(){    int arr[] = {12, 34, 54, 2, 3}, i;    int n = sizeof(arr)/sizeof(arr[0]);     cout << "Array before sorting: \n";    printArray(arr, n);     shellSort(arr, n);     cout << "\nArray after sorting: \n";    printArray(arr, n);     return 0;}
// Java implementation of ShellSortclass ShellSort{    /* An utility function to print array of size n*/    static void printArray(int arr[])    {        int n = arr.length;        for (int i=0; i<n; ++i)            System.out.print(arr[i] + " ");        System.out.println();    }     /* function to sort arr using shellSort */    int sort(int arr[])    {        int n = arr.length;         // 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 a[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 a[i] to the elements that have been gap                // sorted save a[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 a[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 a[i]) in its correct                // location                arr[j] = temp;            }        }        return 0;    }     // Driver method    public static void main(String args[])    {        int arr[] = {12, 34, 54, 2, 3};        System.out.println("Array before sorting");        printArray(arr);         ShellSort ob = new ShellSort();        ob.sort(arr);         System.out.println("Array after sorting");        printArray(arr);    }}/*This code is contributed by Rajat Mishra */
# Python3 program for implementation of Shell Sort def shellSort(arr):    gap = len(arr) // 2 # initialize the gap     while gap > 0:        i = 0        j = gap                 # check the array in from left to right        # till the last possible index of j        while j < len(arr):                 if arr[i] >arr[j]:                arr[i],arr[j] = arr[j],arr[i]                         i += 1            j += 1                     # now, we look back from ith index to the left            # we swap the values which are not in the right order.            k = i            while k - gap > -1:                 if arr[k - gap] > arr[k]:                    arr[k-gap],arr[k] = arr[k],arr[k-gap]                k -= 1         gap //= 2  # driver to check the codearr2 = [12, 34, 54, 2, 3]print("input array:",arr2) shellSort(arr2)print("sorted array",arr2) # This code is contributed by Shubham Prashar (SirPrashar)
// C# implementation of ShellSortusing System; class ShellSort{    /* An utility function to       print array of size n*/    static void printArray(int []arr)    {        int n = arr.Length;        for (int i=0; i<n; ++i)        Console.Write(arr[i] + " ");        Console.WriteLine();    }     /* function to sort arr using shellSort */    int sort(int []arr)    {        int n = arr.Length;         // 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 a[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 a[i] to the elements that have                // been gap sorted save a[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 a[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 a[i])                // in its correct location                arr[j] = temp;            }        }        return 0;    }     // Driver method    public static void Main()    {        int []arr = {12, 34, 54, 2, 3};        Console.Write("Array before sorting :\n");        printArray(arr);         ShellSort ob = new ShellSort();        ob.sort(arr);         Console.Write("Array after sorting :\n");        printArray(arr);    }} // This code is contributed by nitin mittal.
<script>// Javascript implementation of ShellSort /* An utility function to print array of size n*/function printArray(arr){    let n = arr.length;        for (let i = 0; i < n; ++i)            document.write(arr[i] + " ");        document.write("<br>");} /* function to sort arr using shellSort */function sort(arr){    let n = arr.length;          // Start with a big gap, then reduce the gap        for (let gap = Math.floor(n/2); gap > 0; gap = Math.floor(gap/2))        {                     // Do a gapped insertion sort for this gap size.            // The first gap elements a[0..gap-1] are already            // in gapped order keep adding one more element            // until the entire array is gap sorted            for (let i = gap; i < n; i += 1)            {                             // add a[i] to the elements that have been gap                // sorted save a[i] in temp and make a hole at                // position i                let temp = arr[i];                  // shift earlier gap-sorted elements up until                // the correct location for a[i] is found                let j;                for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)                    arr[j] = arr[j - gap];                  // put temp (the original a[i]) in its correct                // location                arr[j] = temp;            }        }        return arr;} // Driver methodlet arr = [12, 34, 54, 2, 3];document.write("Array before sorting<br>");printArray(arr); arr = sort(arr);document.write("Array after sorting<br>");printArray(arr); // This code is contributed by unknown2108</script>
Output:
Array before sorting:
12 34 54 2 3
Array after sorting:
2 3 12 34 54
 
Time Complexity: Time complexity of above implementation of shellsort is O(n2). In the above implementation gap is reduce by half in every iteration. There are many other ways to reduce gap which lead to better time complexity. See this for more details.
References: https://www.youtube.com/watch?v=pGhazjsFW28 http://en.wikipedia.org/wiki/Shellsort
YouTubeGeeksforGeeks500K subscribersShell Sort | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:57•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=SHcPqUe2GZM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Snapshots:  
 
 
 
 
 
Other Sorting Algorithms on GeeksforGeeks/GeeksQuiz: 
Selection Sort
Bubble Sort
Insertion Sort
Merge Sort
Heap Sort
QuickSort
Radix Sort
Counting Sort
Bucket Sort
nitin mittal
NikitaZakharov
shubhamprashar
unknown2108
asdhamidi
sweetyty
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Sort an array of 0s, 1s and 2s
k largest(or smallest) elements in an array
Count Inversions in an array | Set 1 (Using Merge Sort)
Python Program for Bubble Sort
sort() in Python
Merge Sort for Linked Lists
Python List sort() method
Python Program for QuickSort
Most frequent element in an array