-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.py
80 lines (61 loc) · 1.86 KB
/
merge.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#-----------------------------------------------------------------------
# merge.py
#-----------------------------------------------------------------------
import sys
import stdlib.stdio as stdio
import stdlib.stdarray as stdarray
#-----------------------------------------------------------------------
# Merge a[lo:mid] with a[mid:hi] using aux as auxiliary memory.
def _merge(a, lo, mid, hi, aux):
n = hi - lo
i = lo
j = mid
for k in range(n):
if i == mid:
aux[k] = a[j]
j += 1
elif j == hi:
aux[k] = a[i]
i += 1
elif a[j] < a[i]:
aux[k] = a[j]
j += 1
else:
aux[k] = a[i]
i += 1
a[lo:hi] = aux[0:n]
#-----------------------------------------------------------------------
# Sort a[lo:hi] into increasing order, using array aux as auxiliary
# memory.
def _sort(a, lo, hi, aux):
n = hi - lo
if n <= 1:
return
mid = (lo + hi) // 2
_sort(a, lo, mid, aux)
_sort(a, mid, hi, aux)
_merge(a, lo, mid, hi, aux)
#-----------------------------------------------------------------------
# Sort array a into increasing order.
def sort(a):
n = len(a)
aux = stdarray.create1D(n)
_sort(a, 0, n, aux)
#-----------------------------------------------------------------------
# Read strings from standard input, sort them into
# increasing order, and write them to standard output.
def main():
a = stdio.readAllStrings()
sort(a)
for s in a:
stdio.write(s + ' ')
stdio.writeln()
if __name__ == '__main__':
main()
#-----------------------------------------------------------------------
# more tiny.txt
# the and was his you tom but for had him
# python merge.py < tiny.txt
# and but for had him his the tom was you
# python insertion.py < tomsawyer.txt
# ... (Works quickly.)