How to Implement Shell Sort in C Programming?

Shell Sort (aka shellsort) can be thought as an improvement over insertion sort. To understand shell sort, we have to recall how insertion sort works. In insertion sort at any moment, the whole array is sub-divided in two sections, one is sorted and another is not. One element is picked from the unsorted section and compares with the elements of sorted section one by one to get the right position for that element. We may need to compare with all elements of the sorted section to get the right position of the new element. This might happen for many or most of the elements. To improve this situation, in shell sort the insertion sort is done with the far apart elements first. In this process, some out-of-place elements will come to their right locations without needing too many comparisons. Then the gap between the elements, insertion sort is applied with, is reduced gradually. The algorithm stops after applying the insertion sort with gap 1.

Shell Sort Implementation in C


Performance of Shell Sort

Running time of shell sort is still a subject of study but in most cases it is O(N2). Its performance is heavily dependent on the selection of gaps. But in most cases, the actual number of comparisons required is much less than the insertion sort.
The diagram below shows an experimental result how shell sort performs with respect to insertion sort with the increase of number of elements. Randomly ordered arrays were used for this experiment.

Shell Sort performance with respect to insertion sort

From the graph, we can see how performance improved significantly if we sort the far apart elements first then reduce the gap gradually till 1 than to apply insertion with gap 1.

Note: Similar concept can be applied on top of bubble sort also. We can apply bubble sort on far apart elements, then gradually reduce the gap to 1. This sort is also called shell sort.

Leave a Reply

Your email address will not be published. Required fields are marked *