Shell Sort
Shell Sort
Shell Sort
Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm. This algorithm avoids large shifts as in case
of insertion sort, if the smaller value is to the far right and has to be moved to the far left.
This algorithm uses insertion sort on a widely spread elements, first to sort them and then sorts the less widely spaced elements.
This spacing is termed as interval. This interval is calculated based on Knuth's formula as −
Knuth's Formula
h = h * 3 + 1
where −
h is interval with initial value 1
This algorithm is quite efficient for medium-sized data sets as its average and worst-case complexity of this algorithm depends on the
gap sequence the best known is Ο(n), where n is the number of items. And the worst case space complexity is O(n).
https://www.tutorialspoint.com/data_structures_algorithms/shell_sort_algorithm.htm 1/6
7/30/2021 Data Structure and Algorithms - Shell Sort - Tutorialspoint
We compare values in each sub-list and swap them (if necessary) in the original array. After this step, the new array should look like
this −
Then, we take interval of 1 and this gap generates two sub-lists - {14, 27, 35, 42}, {19, 10, 33, 44}
https://www.tutorialspoint.com/data_structures_algorithms/shell_sort_algorithm.htm 2/6
7/30/2021 Data Structure and Algorithms - Shell Sort - Tutorialspoint
We compare and swap the values, if required, in the original array. After this step, the array should look like this −
Finally, we sort the rest of the array using interval of value 1. Shell sort uses insertion sort to sort the array.
Following is the step-by-step depiction −
https://www.tutorialspoint.com/data_structures_algorithms/shell_sort_algorithm.htm 3/6
7/30/2021 Data Structure and Algorithms - Shell Sort - Tutorialspoint
https://www.tutorialspoint.com/data_structures_algorithms/shell_sort_algorithm.htm 4/6
7/30/2021 Data Structure and Algorithms - Shell Sort - Tutorialspoint
We see that it required only four swaps to sort the rest of the array.
Algorithm
Following is the algorithm for shell sort.
Pseudocode
Following is the pseudocode for shell sort.
procedure shellSort()
A : array of items
/* calculate interval*/
while interval < A.length /3 do:
interval = interval * 3 + 1
end while
https://www.tutorialspoint.com/data_structures_algorithms/shell_sort_algorithm.htm 5/6
7/30/2021 Data Structure and Algorithms - Shell Sort - Tutorialspoint
end for
/* calculate interval*/
interval = (interval -1) /3;
end while
end procedure
To know about shell sort implementation in C programming language, please click here .
https://www.tutorialspoint.com/data_structures_algorithms/shell_sort_algorithm.htm 6/6