|
| 1 | +""" |
| 2 | +Implementation of iterative merge sort in Python |
| 3 | +Author: Aman Gupta |
| 4 | +
|
| 5 | +For doctests run following command: |
| 6 | +python3 -m doctest -v iterative_merge_sort.py |
| 7 | +
|
| 8 | +For manual testing run: |
| 9 | +python3 iterative_merge_sort.py |
| 10 | +""" |
| 11 | + |
| 12 | +from typing import List |
| 13 | + |
| 14 | + |
| 15 | +def merge(input_list: List, low: int, mid: int, high: int) -> List: |
| 16 | + """ |
| 17 | + sorting left-half and right-half individually |
| 18 | + then merging them into result |
| 19 | + """ |
| 20 | + result = [] |
| 21 | + left, right = input_list[low:mid], input_list[mid : high + 1] |
| 22 | + while left and right: |
| 23 | + result.append((left if left[0] <= right[0] else right).pop(0)) |
| 24 | + input_list[low : high + 1] = result + left + right |
| 25 | + return input_list |
| 26 | + |
| 27 | + |
| 28 | +# iteration over the unsorted list |
| 29 | +def iter_merge_sort(input_list: List) -> List: |
| 30 | + """ |
| 31 | + Return a sorted copy of the input list |
| 32 | +
|
| 33 | + >>> iter_merge_sort([5, 9, 8, 7, 1, 2, 7]) |
| 34 | + [1, 2, 5, 7, 7, 8, 9] |
| 35 | + >>> iter_merge_sort([6]) |
| 36 | + [6] |
| 37 | + >>> iter_merge_sort([]) |
| 38 | + [] |
| 39 | + >>> iter_merge_sort([-2, -9, -1, -4]) |
| 40 | + [-9, -4, -2, -1] |
| 41 | + >>> iter_merge_sort([1.1, 1, 0.0, -1, -1.1]) |
| 42 | + [-1.1, -1, 0.0, 1, 1.1] |
| 43 | + >>> iter_merge_sort(['c', 'b', 'a']) |
| 44 | + ['a', 'b', 'c'] |
| 45 | + >>> iter_merge_sort('cba') |
| 46 | + ['a', 'b', 'c'] |
| 47 | + """ |
| 48 | + if len(input_list) <= 1: |
| 49 | + return input_list |
| 50 | + input_list = list(input_list) |
| 51 | + |
| 52 | + # iteration for two-way merging |
| 53 | + p = 2 |
| 54 | + while p < len(input_list): |
| 55 | + # getting low, high and middle value for merge-sort of single list |
| 56 | + for i in range(0, len(input_list), p): |
| 57 | + low = i |
| 58 | + high = i + p - 1 |
| 59 | + mid = (low + high + 1) // 2 |
| 60 | + input_list = merge(input_list, low, mid, high) |
| 61 | + # final merge of last two parts |
| 62 | + if p * 2 >= len(input_list): |
| 63 | + mid = i |
| 64 | + input_list = merge(input_list, 0, mid, len(input_list) - 1) |
| 65 | + p *= 2 |
| 66 | + |
| 67 | + return input_list |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == "__main__": |
| 71 | + user_input = input("Enter numbers separated by a comma:\n").strip() |
| 72 | + unsorted = [int(item.strip()) for item in user_input.split(",")] |
| 73 | + print(iter_merge_sort(unsorted)) |
0 commit comments