Anda di halaman 1dari 22

Shell Sort

Chapter-4

Bucket sort

Bucket sort example

Bucket sort Example 2

Shell Sort
Shell sort works by comparing elements that are distant rather than adjacent elements in an array. Shell sort improves on the efficiency of insertion sort by quickly shifting values to their destination. Shell sort is also known as diminishing increment sort. The distance between comparisons decreases as the sorting algorithm runs until the last phase in which adjacent elements are compared

Shell Sort
18 32 12 5 38 33 16 2 floor(8/2) floor(4) = 4 18 32 12 5 38 33 16 2 Resulting numbers after increment 4 pass: 18 32 12 2 38 33 16 5

Shell Sort
floor(4/2) floor(2) = 2

increment 2: 18 32 12 2 38 33 16 5 Again sort the column.

Shell Sort
The result is, 12 16 18 38 2 5 32 33

Shell Sort
floor(2/2) floor(1) = 1 12 2 16 5 18 32 38 33 The last increment or phase of Shell sort is basically an Insertion Sort algorithm. 2 5 12 16 18 32 33 38

Shell Sort
Arrange the list into a table and sort the columns (using an insertion sort). Repeat this process, each time with smaller number of longer columns. At the end, the table has only one column.

For example, consider a list of numbers like [ 13 14 94 33 82 25 59 94 65 23 45 27 73 25 39 10 ]. If we started with a step-size of 5, we could visualize this as breaking the list of numbers into a table with 5 columns.

Example
This would look like this: 13 14 94 33 82 25 59 94 65 23 45 27 73 25 39 10

Example Contd
We then sort each column, which gives us 10 14 73 25 23 13 27 94 33 39 25 59 94 65 82 45

Example Contd
When read back as a single list of numbers, we get [ 10 14 73 25 23 13 27 94 33 39 25 59 94 65 82 45 ]. Here, the 10 which was all the way at the end, has moved all the way to the beginning. This list is then again sorted using a 3-gap sort as shown below.

Example Contd
10 14 73 25 23 13 27 94 33 39 25 59 94 65 82 45 Again sort each column

Example Contd
Which gives us 10 14 13 25 23 33 27 25 59 39 65 73 45 94 82 94 Now all that remains to be done is a 1-gap sort (simple insertion sort).

INTERPOLATION SEARCH:
It is a modified algorithm of Binary search reducing the complexity. Best/Average case complexity is O(log log n) ) which will occur when elements of the array are fairly uniformly distributed over their interval eg. . [3,5,8,10,13,15] Worst case complexity is O(n) which will occur when the elements are not fairly uniformly distributed over their interval eg. [3,5,8,10,13,100]

Example:
Search for the key 20 in the following array using Interpolation Search int[] a = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30}

Interpolation Search:
middle = low + ( high - low )*( (key a[low]) / ( a[high] a[low] ))

middle = 0 + ceil(15 0)* ( (20 0) / (30 0) ) = 0 +10 =10 a[middle] = 20 which is equal to key. So key found at index 10.

Anda mungkin juga menyukai