Summary: In this tutorial, we will learn what Shell Sort Algorithm is, how it works and how to sort an array using the Shell Sort Algorithm in C, C++, and Java.

Introduction to Shell Sort Algorithm

Shell Sort is an optimization of insertion sort that allows the exchange of items that are far apart.


Shell Sort Algorithm introduces a gap in the sorting process which quickly reduces the amount of disorder in the array compared to the insertion sort algorithm.

In Insertion sort, the value of the gap is one. That’s why in insertion sort we compare an array element with its adjacent element of 1 index far way.

But in shell sort instead of comparing the values one index away, we compare values with the index difference of gap=length/2 and decrease the gap value successively.

Beginning with a large gap value leaves less work for smaller gap values to finish the sorting process.

When the gap reduces to 1, the shell sort behaves as insertion sort.

Here is the illustration of how shell sorts works:

Shell sort with gap of 3
shell sort with gap of 4

Shell Sort Algorithm

  1. Initialize gap=(size_of_array/2).
  2. Loop from j=gap to i<size_of array.
  3. while (arr[j-gap] > arr[j] && j>=gap) swap (arr[j-gap], arr[j]).
  4. End Loop.
  5. Update gap=gap/2 and repeat for gap>=1 from step-1.

Here is the implementation of the shell sort algorithm in C, C++, and Java:





Shell Sort Overview

  • In-place algorithm: No extra array is used
  • O(n²) worst-case time complexity: The time complexity depends on the gap value.
  • Unstable algorithm: Duplicates numbers are not interchanged.

In this tutorial, we learned what is shell sort algorithm, how it works and how to sort an array in C, C++, and Java using shell sort algorithm.

Leave a Reply

4 + 2 =