|
| 1 | +def merge(seq, start, mid, stop): |
| 2 | + """ |
| 3 | + merge lists (sub-lists) that have been sorted |
| 4 | + """ |
| 5 | + |
| 6 | + lst = [] |
| 7 | + _start = start |
| 8 | + _mid = mid |
| 9 | + |
| 10 | + while _start < mid and _mid < stop: |
| 11 | + if seq[_start] < seq[_mid]: |
| 12 | + lst.append(seq[_start]) |
| 13 | + _start += 1 |
| 14 | + else: |
| 15 | + lst.append(seq[_mid]) |
| 16 | + _mid += 1 |
| 17 | + |
| 18 | + # leftover |
| 19 | + while _start < mid: |
| 20 | + lst.append(seq[_start]) |
| 21 | + _start += 1 |
| 22 | + |
| 23 | + # copy the items back to the original sequence |
| 24 | + for idx in range(len(lst)): |
| 25 | + seq[start + idx] = lst[idx] |
| 26 | + |
| 27 | + |
| 28 | +def merge_sort_recursive(seq, start, stop): |
| 29 | + """ |
| 30 | + a helper function to get things (split & sort) started |
| 31 | + """ |
| 32 | + |
| 33 | + if start >= stop - 1: |
| 34 | + return None |
| 35 | + |
| 36 | + mid = (start + stop) // 2 |
| 37 | + |
| 38 | + merge_sort_recursive(seq, start, mid) |
| 39 | + merge_sort_recursive(seq, mid, stop) |
| 40 | + |
| 41 | + # half, half-of-half, half-of-half-of-half -> merge |
| 42 | + # half, half-of-half, half-of-half-of-half -> merge another |
| 43 | + # merge both -> the end |
| 44 | + merge(seq, start, mid, stop) |
| 45 | + |
| 46 | + |
| 47 | +def merge_sort(seq): |
| 48 | + """ |
| 49 | + O(N logN) |
| 50 | + O(logN) for dividing the list into lists of size 1 |
| 51 | + O(N) for merging the sorted sublists |
| 52 | + """ |
| 53 | + merge_sort_recursive(seq, 0, len(seq)) |
| 54 | + |
| 55 | + |
| 56 | +def main(): |
| 57 | + """ |
| 58 | + Not 100% percent get this algorithm, but nearly done :) |
| 59 | + """ |
| 60 | + d, d_sorted = [3, 7, 9, 40, 1, 13, 10], [1, 3, 7, 9, 10, 13, 40] |
| 61 | + merge_sort(d) |
| 62 | + assert d == d_sorted |
| 63 | + |
| 64 | + |
| 65 | +if "__main__" == __name__: |
| 66 | + main() |
0 commit comments