Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell sort and insertion sort

I got a problem. I'm very confused over shell sort and insertion sort algorithms. How should we distinguish from each other?

like image 775
Rhokai Avatar asked Jan 31 '13 06:01

Rhokai


2 Answers

Shell sort is a generalized version of Insertion sort. The basic priciple is the same for both algorithms. You have a sorted sequence of length n and you insert the unsorted element into it - and you get n+1 elements long sorted sequence.

The difference follows: while Insertion sort works only with one sequence (initially the first element of the array) and expands it (using the next element). However, shell sort has a diminishing increment, which means, that there is a gap between the compared elements (initially n/2). Hence there are n/2 sequences to be sorted using insertion sort. In each step the increment is shrinked (often just divided by 2.2) and the number of sequences is reduced. In the last step there is no gap and the algorithm degenerates to simple insertion sort.

Because of the diminishing increment, the large and small elements are moved rapidly to correct part of the array and than in the last step sorted using insertion sort really fast. This leads to reduced time complexity O(n^(4/3))

like image 136
malejpavouk Avatar answered Oct 13 '22 12:10

malejpavouk


You can implement insertion sort as a series of comparisons and swaps of contiguous elements. That makes it a "stable sort". Shell sort, instead, compares and swaps elements which are far from each other. That makes it faster.

I suppose that your confusion comes from the fact that shell sort can be implemented as several insertion sorts applied to different subsets of the data. Note that these subsets are composed of noncontiguous elements of the data sequence.

See the Wikipedia for more details ;-)

like image 28
comocomocomocomo Avatar answered Oct 13 '22 12:10

comocomocomocomo