# 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 log^{2}n) |

Time Complexity: Worst | O(n^{2}) |

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) { shellSort(collection); } 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.

### Conclusion

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.