This document contains the code for an iterative merge sort algorithm in Python. It takes an iterable as input, splits it recursively into single element lists, and then iteratively merges the sorted runs back together. Key functions include iter_merge to yield the merged elements, and msort for the recursive splitting and merging steps. The full merge_sort function handles preprocessing if a key function is provided before recursively calling msort.
This document contains the code for an iterative merge sort algorithm in Python. It takes an iterable as input, splits it recursively into single element lists, and then iteratively merges the sorted runs back together. Key functions include iter_merge to yield the merged elements, and msort for the recursive splitting and merging steps. The full merge_sort function handles preprocessing if a key function is provided before recursively calling msort.
This document contains the code for an iterative merge sort algorithm in Python. It takes an iterable as input, splits it recursively into single element lists, and then iteratively merges the sorted runs back together. Key functions include iter_merge to yield the merged elements, and msort for the recursive splitting and merging steps. The full merge_sort function handles preprocessing if a key function is provided before recursively calling msort.
/home/pablo/Dropbox/02 - Docencia/Paradigmas de Programación/code/python/msort.
py
1 next_item = lambda it: next(it, None)
2 3 def iter_merge(iter_a, iter_b, lt): 4 5 a = next_item(iter_a) 6 b = next_item(iter_b) 7 8 while not a is None and not b is None: 9 if lt(a, b): 10 yield a 11 a = next_item(iter_a) 12 else: 13 yield b 14 b = next_item(iter_b) 15 16 while not a is None: 17 yield a 18 a = next_item(iter_a) 19 20 while not b is None: 21 yield b 22 b = next_item(iter_b) 23 24 def merge_sort(A, key = None): 25 26 Source = A 27 28 if key is None: 29 lt = lambda x,y: x < y 30 else: 31 A = [(key(x),x) for x in A] 32 lt = lambda x,y: x[0] < y[0] 33 34 msort(A, 0, len(A) - 1, lt, [0]*len(A)) 35 36 if key is not None: 37 Source[0:] = (x[1] for x in A) 38 39 def msort(A, s, t, lt, B): 40 if s < t: 41 m = (s + t) // 2 42 msort(A, s, m, lt, B) 43 msort(A, m+1, t, lt, B) 44 A[s:t+1] = iter_merge((A[i] for i in xrange(s,m+1)) , (A[i] for i in xrange(m+1,t+1)), lt)
Ten-Decimal Tables of the Logarithms of Complex Numbers and for the Transformation from Cartesian to Polar Coordinates: Volume 33 in Mathematical Tables Series