|
| 1 | +def timsort(array): |
| 2 | + min_run = 32 |
| 3 | + n = len(array) |
| 4 | + |
| 5 | + # Start by slicing and sorting small portions of the |
| 6 | + # input array. The size of these slices is defined by |
| 7 | + # your `min_run` size. |
| 8 | + for i in range(0, n, min_run): |
| 9 | + insertion_sort(array, i, min((i + min_run - 1), n - 1)) |
| 10 | + |
| 11 | + # Now you can start merging the sorted slices. |
| 12 | + # Start from `min_run`, doubling the size on |
| 13 | + # each iteration until you surpass the length of |
| 14 | + # the array. |
| 15 | + size = min_run |
| 16 | + while size < n: |
| 17 | + # Determine the arrays that will |
| 18 | + # be merged together |
| 19 | + for start in range(0, n, size * 2): |
| 20 | + # Compute the `midpoint` (where the first array ends |
| 21 | + # and the second starts) and the `endpoint` (where |
| 22 | + # the second array ends) |
| 23 | + midpoint = start + size - 1 |
| 24 | + end = min((start + size * 2 - 1), (n-1)) |
| 25 | + |
| 26 | + # Merge the two subarrays. |
| 27 | + # The `left` array should go from `start` to |
| 28 | + # `midpoint + 1`, while the `right` array should |
| 29 | + # go from `midpoint + 1` to `end + 1`. |
| 30 | + merged_array = merge( |
| 31 | + left=array[start:midpoint + 1], |
| 32 | + right=array[midpoint + 1:end + 1]) |
| 33 | + |
| 34 | + # Finally, put the merged array back into |
| 35 | + # your array |
| 36 | + array[start:start + len(merged_array)] = merged_array |
| 37 | + |
| 38 | + # Each iteration should double the size of your arrays |
| 39 | + size *= 2 |
| 40 | + |
| 41 | + return array |
0 commit comments