DEV Community

André Maré
André Maré

Posted on • Originally published at on

Shell Sort Algorithm in Java

Shell Sort is an in-place comparison sort algorithm. Shell Sort is a generalization of insertion sort that allows the exchange of items that are far apart. The algorithm perform preliminary work by sorting pairs of elements far apart from each other. The algorithm progressively reduce the gap between elements to be compared as the goal is to reduce the amount of shifting of elements across the array. As the gap is reduced to 1, the algorithm becomes the same as the insertion sort algorithm.

Algorithm Classification

The following table contains information about the analysis of the Shell Sort Sort algorithm. It defines the worst, average and best cases in terms of time complexity and also the worst case in space complexity.

Attribute Value
Class Sorting Algorithm
Classification Internal, In-place, Unstable Algorithm
Data Structure Array
Time Complexity: Best Ω(n log(n))
Time Complexity: Average Θ(n log2n)
Time Complexity: Worst O(n2)
Space Complexity: Worst O(1)

Please use the following link for an explanation on Big-O notation and what is good, fair and bad.

Shell Sort In Java

public final class ShellSort {

    public void sort(int[] collection) {
        if (collection != null) {
        } else {
            throw new IllegalArgumentException("Input paramenter for array to sort is null.");

    private void shellSort(int[] collection) {
        int arrayLength = collection.length;

        for (int gap = arrayLength / 2; gap > 0; gap /= 2) {
            for (int i = gap; i < arrayLength; i++) {
                int newElement = collection[i];

                int j = i;
                while (j >= gap && collection[j - gap] > newElement) {
                    collection[j] = collection[j - gap];
                    j -= gap;
                collection[j] = newElement;

Sample Code (GitHub)

The details of the Shell Sort class can be viewed here.

The details of the Shell Sort JUnit Test class can be viewed here.


The Shell Sort algorithm forms part of a larger group of sorting algorithms. Learning through experience is the reason I created this post about the implementation of the Shell Sort algorithm in Java. I have learned a lot about how others have solved the Shell Sort algorithm in other languages including different implementations in Java.

The post Shell Sort Algorithm in Java appeared first on Code2Bits.

Top comments (0)