|
| 1 | +""" |
| 2 | +This function implements the shell sort algorithm |
| 3 | +which is slightly faster than its pure implementation. |
| 4 | +
|
| 5 | +This shell sort is implemented using a gap, which |
| 6 | +shrinks by a certain factor each iteration. In this |
| 7 | +implementation, the gap is initially set to the |
| 8 | +length of the collection. The gap is then reduced by |
| 9 | +a certain factor (1.3) each iteration. |
| 10 | +
|
| 11 | +For each iteration, the algorithm compares elements |
| 12 | +that are a certain number of positions apart |
| 13 | +(determined by the gap). If the element at the higher |
| 14 | +position is greater than the element at the lower |
| 15 | +position, the two elements are swapped. The process |
| 16 | +is repeated until the gap is equal to 1. |
| 17 | +
|
| 18 | +The reason this is more efficient is that it reduces |
| 19 | +the number of comparisons that need to be made. By |
| 20 | +using a smaller gap, the list is sorted more quickly. |
| 21 | +""" |
| 22 | + |
| 23 | + |
| 24 | +def shell_sort(collection: list) -> list: |
| 25 | + """Implementation of shell sort algorithm in Python |
| 26 | + :param collection: Some mutable ordered collection with heterogeneous |
| 27 | + comparable items inside |
| 28 | + :return: the same collection ordered by ascending |
| 29 | +
|
| 30 | + >>> shell_sort([3, 2, 1]) |
| 31 | + [1, 2, 3] |
| 32 | + >>> shell_sort([]) |
| 33 | + [] |
| 34 | + >>> shell_sort([1]) |
| 35 | + [1] |
| 36 | + """ |
| 37 | + |
| 38 | + # Choose an initial gap value |
| 39 | + gap = len(collection) |
| 40 | + |
| 41 | + # Set the gap value to be decreased by a factor of 1.3 |
| 42 | + # after each iteration |
| 43 | + shrink = 1.3 |
| 44 | + |
| 45 | + # Continue sorting until the gap is 1 |
| 46 | + while gap > 1: |
| 47 | + |
| 48 | + # Decrease the gap value |
| 49 | + gap = int(gap / shrink) |
| 50 | + |
| 51 | + # Sort the elements using insertion sort |
| 52 | + for i in range(gap, len(collection)): |
| 53 | + temp = collection[i] |
| 54 | + j = i |
| 55 | + while j >= gap and collection[j - gap] > temp: |
| 56 | + collection[j] = collection[j - gap] |
| 57 | + j -= gap |
| 58 | + collection[j] = temp |
| 59 | + |
| 60 | + return collection |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + import doctest |
| 65 | + |
| 66 | + doctest.testmod() |
0 commit comments