Friday, February 11, 2011

Shell Sort

  • requires O(N3/2) operations in the worst case, which means that it can be quite effectively used even for moderately large files (say N < 5000).
  • Invented by Donald Shell in 1959, the shell sort is the most efficient of the O(n2) class of sorting algorithms.
  • It is also the most complex of the O(n2) algorithms.
  • The shell sort is a "diminishing increment sort", better known as a "comb sort" to the unwashed programming masses.

Pros: Efficient for medium-size lists.

Cons: Somewhat complex algorithm, not nearly as efficient as the merge, heap, and quick sorts.


The algorithm makes multiple passes through the list, and each time sorts a number of equally sized sets using the insertion sort. The size of the set to be sorted gets larger with each pass through the list, until the set consists of the entire list. (Note that as the size of the set increases, the number of sets to be sorted decreases.) This sets the insertion sort up for an almost-best case run each iteration with a complexity that approaches O(n).


Example and Steps in Shell Sort:

The idea is to divide the sequence into groups which induces great order into the initial random sequence relatively fast and then apply insertion sort to get final order.

To compare element which are relatively great distance from each other,

Steps:

1. half the sequence (4 elements/group), and compare corresponding elements (four groups, two elements/group).



Empirical Analysis

Shell Sort Efficiency

The shell sort is by far the fastest of the N2 class of sorting algorithms. It's more than 5 times faster than the bubble sort and a little over twice as fast as the insertion sort, its closest competitor.


The shell sort is still significantly slower than the merge, heap, and quick sorts, but its relatively simple algorithm makes it a good choice for sorting lists of less than 5000 items unless speed is hyper-critical. It's also an excellent choice for repetitive sorting of smaller lists.


Source Code

Below is the basic shell sort algorithm.


void shellSort(int numbers[], int array_size)

{

int i, j, increment, temp;

increment = 3;

while (increment > 0)

{

for (i=0; i <>

{

j = i;

temp = numbers[i];

while ((j >= increment) && (numbers[j-increment] > temp))

{

numbers[j] = numbers[j - increment];

j = j - increment;

}

numbers[j] = temp;

}

if (increment/2 != 0)

increment = increment/2;

else if (increment == 1)

increment = 0;

else

increment = 1;

}

}

No comments:

Post a Comment