Updated on
Shell sort runs insertion sort on elements a fixed gap apart, then shrinks the gap until it reaches 1. In C#, it fits in one method with three nested loops and no extra array.
Have you ever needed to sort a list of items, but didn’t want to use the built-in sorting function? Shell sort is a good one to learn next. We’ll see how it works, implement it, and measure it, including the one input that makes it quadratic, like insertion sort.
Let’s dive in.
What Is Shell Sort?
This algorithm was created by Donald Shell in 1959. It works based on the premise that sorting further elements first effectively reduces the interval between the elements that still need to undergo the sorting process. This makes the shell sort algorithm work in the same way as a generalized version of the insertion sort algorithm.Â
The algorithm sorts elements at a specific interval first and reduces that interval gradually until it is equal to one. It supports different interval selection strategies such as:Â
- Shell’s original sequence (N/2, N/4, …, 1), where N is the length of the array
- Knuth’s sequence: 1, 4, 13, 40, …, (3k − 1) / 2
- Sedgewick’s sequence: 1, 8, 23, 77, 281…
- Hibbard’s sequence: 1, 3, 7, 15, 31, 63…
The algorithm may perform differently depending on the interval strategy in use but to keep this article simple, we are going to use Shell’s original sequence.Â
Let’s take a deep dive and learn how shell sort works.Â
How Does the Shell Sort Algorithm Work?
Let’s look at an example of how shell sort works. We will use the following set of numbers:
int[] array = {34, 31, 39, 9, 15, 19, 26, 44};
When using Shell’s original sequence, we are going to start from N/2, with N being the array’s length (8).
Iteration One
We compare and swap the elements lying at the interval of 4. For example, the element at index zero gets compared with the element at index four in the array.Â
With that in mind, at the interval of 4, here are the sublists that we have: {34, 15}, {31, 19}, {39, 26}, {9, 44}
Next, we are going to compare the elements in these sublists and swap their positions in the original array accordingly:
15, 19, 26, 9, 34, 31, 39, 44
Here, we can see that some elements swap their positions in the original array after the first iteration.Â
Iteration Two
We set the interval to 2, that is, N/4. These are the conceptual subarrays that we are going to sort next: {15, 26, 34, 39} and {19, 9, 31, 44}.
Once more, we are going to compare these elements and update their positions on the original array, which becomes:
15, 9, 26, 19, 34, 31, 39, 44
Final Iteration
The interval will be equal to 1 (N/8 = 1). We are going to use insertion sort to complete the sorting process.Â
Assuming 15 is a sorted list of the first item, we are going to compare 15 with 9. Since 9 is less than 15, we swap their positions and the array becomes:
9, 15, 26, 19, 34, 31, 39, 44
15 is not greater than 26 while 19 is less than 26 so, we swap their positions, and the array becomes:
9, 15, 19, 26, 34, 31, 39, 44
26 is less than 34 but 31 is less than 34, so we swap their positions to complete the sorting process:Â
9, 15, 19, 26, 31, 34, 39, 44
The last pass needed only three moves, because the gap-4 and gap-2 passes had already carried the far-away elements close to their places.

Shell sort on our eight numbers: gaps of 4, 2 and 1, with each gap’s sublists in matching colors.
Let’s learn how to implement the shell sort algorithm in C#.
How to Implement Shell Sort in C#?
To implement shell sort in C#, we need a loop over the gaps and an insertion sort that compares elements one gap apart.
The outer loop starts the gap at half the array length and halves it after every pass. An array of eight elements gets gaps of 4, 2 and 1, which is Shell’s original sequence.
For each gap, the middle loop takes every element from index gap onward. The inner while loop shifts the larger elements one gap to the right until it finds the right slot, and then the element goes into it.
The last pass, with a gap of 1, is plain insertion sort. On most inputs the earlier passes have already moved each element close to its final place, so that pass has far less work than insertion sort alone would.
The method sorts the array in place, without allocating a second array, and returns the same instance.
In a public ShellSortMethods class of a new console app, let’s write a function ShellSort() that takes an array and its size as inputs and returns the array, sorted in place:
public int[] ShellSort(int[] array, int size)
{
for (int interval = size / 2; interval > 0; interval /= 2)
{
for (int i = interval; i < size; i++)
{
var currentKey = array[i];
var k = i;
while (k >= interval && array[k - interval] > currentKey)
{
array[k] = array[k - interval];
k -= interval;
}
array[k] = currentKey;
}
}
return array;
}
The function implements the shell sort algorithm by using Shell’s original sequence as the outer loop keeps subdividing the gap by two until it gets equal to one. For every gap interval, the function uses insertion sort to compare and swap array elements until the array is sorted.Â
Finally, in a test method of an MSTest project that references our app, we can verify that the ShellSort() method sorts a given unsorted array accurately:
var array = new int[] { 73, 57, 49, 99, 133, 20, 1 };
var expected = new int[] { 1, 20, 49, 57, 73, 99, 133 };
var sortFunction = new ShellSortMethods();
var sortedArray = sortFunction.ShellSort(array, array.Length);
Assert.IsNotNull(sortedArray);
CollectionAssert.AreEqual(expected, sortedArray);
What Is the Time Complexity of Shell Sort?
Shell sort’s time complexity depends on its gap sequence. With Shell’s original sequence, which our code uses, the best case is O(n log n), the worst case is O(n²), and the average case sits between the two.
The sort works in place, so besides the array itself it needs only O(1) extra space for a few local variables.
The best case is an array that is already sorted. Each pass then makes about one comparison per element and moves nothing, and there are about logâ‚‚ n passes. For 65,536 sorted elements, that is 983,041 comparisons.
On random numbers, our counts grow faster than n log n and far slower than n². Ten random arrays of 65,536 elements took between 8.2 and 12.3 million comparisons.
Better gap sequences lower the worst case, down to O(n log² n) for Pratt’s sequence.
Shell sort is not stable, so equal elements can change their order.
Best-Case Time Complexity
The shell sort algorithm encounters its best-case time complexity scenario when it encounters an array that is already sorted. The number of comparisons for every interval is at most the size of the array. Therefore, the algorithm has a best-case time complexity of O(n log n). That holds for the gaps our code uses: 65,536 sorted numbers go through 16 passes, and each pass compares almost every element once with its neighbor one gap back, 983,041 comparisons in total.
Average-Case Time Complexity
The average-case time complexity of shell sort depends on the interval chosen by the programmer. The NIST Dictionary of Algorithms and Data Structures calls the gaps “i values” and says: “A good series of i values is important to efficiency.”
For Shell’s original sequence, there is no simple formula we can quote, so we counted. On ten random arrays of each size, going from 16,384 to 65,536 elements (four times more) took the average from about 1.35 million to about 10.3 million comparisons, between seven and eight times more. An O(n log n) sort would need about 4.6 times more, and an O(n²) sort 16 times more.
Worst-Case Time Complexity
Shell sort has a worst-case time complexity of O(n2). This scenario occurs when we select a poor gap sequence while selecting the best known worst-case gap sequence makes the algorithm have a worst-case time complexity of O(n log2 n). The gap sequence we use in this article operates in quadratic time making it have a time complexity of O(n2).Â
We can simulate worst-case time complexity when using Shell’s original sequence when we put the smallest elements at odd indexes and the largest elements at even indexes. For example, when we try to sort an array such as 11, 2, 12, 4, 13, 6, 14, 8, none of the passes (N/2, N/4, …, 2) rearrange the elements, because every gap above 1 is even and compares even indexes only with even indexes, and odd only with odd. The algorithm moves the elements only in the last pass, when the gap is 1, and that pass is a plain insertion sort that needs 10 moves for our eight numbers. In general, it needs about n²/8 moves, which is still O(n2).
This only works when the array length is a power of two, or one more than a power of two. Any other length runs into an odd gap sooner or later, and an odd gap mixes the two halves early. In our counts, the same pattern took 543 million comparisons for 65,536 numbers and only about 2 million for 65,000.
Advantages of Shell Sort Algorithm
The shell sort algorithm has several advantages, including being efficient when sorting medium size arrays.
Besides that, the algorithm does not require any extra space to run unlike sorting algorithms such as merge sort.
Shell sort performs better than other sorting algorithms such as insertion sort and bubble sort.
On 16,384 random numbers, our shell sort made about 1.4 million comparisons, while a plain insertion sort made about 66.6 million.
Finally, it is adaptive, as its runtime reduces when it encounters an array that is almost sorted.Â
Disadvantages of Shell Sort Algorithm
The shell sort algorithm can be less efficient than other sorting algorithms for large data sets such as merge sort and quicksort. Additionally, the algorithm is not stable, meaning that it may not preserve the order of elements with equal keys just like quicksort.
For example, if we sort the pairs (1, a), (0, b), (0, c), (0, d) by their number, our shell sort returns (0, c), (0, b), (0, d), (1, a). The gap-2 pass swaps (1, a) with (0, c), and (0, c) jumps over (0, b) on its way to the front. Code that needs equal keys to stay in order should use a stable sort such as LINQ’s OrderBy(), covered with the alternatives in our article on sorting a list by a property.
Shell’s gaps can also hit O(n²) on the wrong input, so when we need an in-place sort with a guaranteed O(n log n), heap sort is the closer fit. For production code, Array.Sort() is the better pick, and the algorithm behind it is the subject of our quicksort article.
Performance Tests
Let’s test how long the algorithm takes to sort sorted, random and imbalanced arrays of three sizes with BenchmarkDotNet. To help us complete these tests, we are going to implement three methods in our ShellSortMethods class.
First, let’s write a method to generate a set of random array elements:
public static int[] CreateRandomArray(int size, int lower, int upper)
{
var array = new int[size];
var rand = new Random();
for (int i = 0; i < size; i++)
array[i] = rand.Next(lower, upper);
return array;
}
The CreateRandomArray() method takes three integers size, lower and upper. Using the inbuilt Random class, we generate integer values between lower and upper that we’re going to put into the array.
Next, we are going to simulate the best-case time complexity scenario by defining a method CreateSortedArray() that returns a sorted array:Â
public static int[] CreateSortedArray(int size)
{
var array = new int[size];
for (int i = 0; i < size; i++)
array[i] = i;
return array;
}
To simulate the worst-case time complexity scenario, we are going to use CreateRandomArray() we have but tweak it in such a way that we have small elements at odd indexes and larger elements at even indexes in the array:
public static int[] CreateImbalancedArray(int size, int lower, int upper)
{
var array = new int[size];
var rand = new Random();
for (int i = 0; i < size; i++)
{
if ((i % 2) == 0)
{
array[i] = rand.Next(upper/2, upper);
}
else
{
array[i] = rand.Next(lower, 1000);
}
}
return array;
}
Here, we see that we place random numbers between lower and 1000 at odd indexes in the array and larger elements between upper/2 and upper at even indexes of the array.Â
This array is a worst case when its length is a power of two, as we saw in the worst-case section, so our benchmark uses sizes of 4,096, 16,384 and 65,536.
Benchmark Setup
Since ShellSort() works in place, the first benchmark call leaves its input sorted. BenchmarkDotNet then calls the method again and again, so with one shared array, every later call would time the best case, whatever input we named.
So that each call starts from the same unsorted numbers, Setup() stores the generated array, and the benchmark copies it into a working array before it sorts:
public class ShellSortBenchmarks
{
private readonly ShellSortMethods _sortMethods = new();
private int[] _source = [];
private int[] _work = [];
[Params(4_096, 16_384, 65_536)]
public int Size { get; set; }
[Params("Sorted", "Random", "Imbalanced")]
public string Input { get; set; } = "Random";
[GlobalSetup]
public void Setup()
{
_source = Input switch
{
"Sorted" => ShellSortMethods.CreateSortedArray(Size),
"Random" => ShellSortMethods.CreateRandomArray(Size, 1, 2_000_000),
_ => ShellSortMethods.CreateImbalancedArray(Size, 1, 2_000_000)
};
_work = new int[Size];
}
[Benchmark]
public int[] ShellSort()
{
_source.CopyTo(_work, 0);
return _sortMethods.ShellSort(_work, Size);
}
}
For each Size and Input pair, Setup() fills the source array once, before any timing starts. The random and imbalanced arrays draw their numbers from 1 to 2,000,000, so the small values below 1,000 and the large ones from 1,000,000 up never overlap. Copying costs O(n), which is small next to the sort itself.
Sample Test Results
The class goes in its own file in our console app. We add the BenchmarkDotNet package to the app, start the class file with using BenchmarkDotNet.Attributes;, and call BenchmarkRunner.Run<ShellSortBenchmarks>(); from its Program.cs, after using BenchmarkDotNet.Running;. Let’s run it in Release mode and assess the sample best, average, and worst-case complexity performance results of the algorithm:
| Method | Size | Input | Mean | Error | StdDev | |---------- |------ |----------- |--------------:|-------------:|-------------:| | ShellSort | 4096 | Imbalanced | 1,687.60 us | 21.092 us | 17.613 us | | ShellSort | 4096 | Random | 343.56 us | 3.978 us | 3.526 us | | ShellSort | 4096 | Sorted | 34.65 us | 0.657 us | 0.549 us | | ShellSort | 16384 | Imbalanced | 22,587.31 us | 140.621 us | 124.657 us | | ShellSort | 16384 | Random | 1,938.80 us | 9.057 us | 8.029 us | | ShellSort | 16384 | Sorted | 160.72 us | 0.139 us | 0.116 us | | ShellSort | 65536 | Imbalanced | 316,380.29 us | 3,112.319 us | 2,758.990 us | | ShellSort | 65536 | Random | 12,265.17 us | 78.803 us | 69.856 us | | ShellSort | 65536 | Sorted | 742.38 us | 0.790 us | 0.660 us |
As we can see, the three inputs take very different times, even though they have the same number of elements.
The sorted arrays are the best case. 65,536 sorted numbers take about 0.75 milliseconds, and the time grows roughly in step with the size.
Random arrays, our average case, take about 12 milliseconds at 65,536 elements, roughly 16 times the sorted time.
The imbalanced arrays are the worst case. At 65,536 elements they take about 0.32 seconds, roughly 25 times the random time. Going from 16,384 to 65,536 elements makes them about 14 times slower, close to the 16 times that O(n²) predicts for four times more data.
Please note that these runtimes may change depending on the number of elements and the computing resources available.Â
Conclusion
In summary, shell sort uses this working principle:
- DETERMINE the size of the intervals going to be used
- DIVIDE the array into conceptual subarrays using the elements whose distance is determined by the interval
- SORT the conceptual subarrays in place
- SHORTEN the gap by half (Shell’s sequence)
- REPEAT the steps above until the interval is equal to 1 and use insertion sort to complete the sorting process
In this article, we have learned how shell sort in C# works and its time and space complexity.
With Shell’s original gaps, shell sort beats insertion sort by a wide margin on random data, and an array of power-of-two length with the right pattern can still push it back to O(n²). If you want to see where the idea started, our insertion sort article is the natural next read.
Tested with .NET 10.0.10, BenchmarkDotNet 0.15.8 and MSTest 4.5.2.






