-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_sort.py
66 lines (51 loc) · 1.17 KB
/
merge_sort.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
#!/usr/bin/env python
'''Implementation of top-down MergeSort, using in-place array merges.'''
import sys
def stdin_to_ints(stream):
clean_str = [x.replace('\n', '') for x in stream.next().split(' ')]
return [int(x) for x in clean_str]
def less(n, m):
return n < m
def merge(a, lo, mid, hi):
temp = []
for num in a:
temp.append(num)
j = lo
k = mid + 1
for ix, num in enumerate(a):
if j > mid:
a[ix] = k
k += 1
if k > hi:
a[ix] = j
j += 1
elif less(j, k):
a[ix] = j
j += 1
else:
a[ix] = k
k += 1
def sort(a, lo, hi):
if lo == hi:
return
mid = lo + (hi - lo) / 2
sort(a, lo, mid)
sort(a, mid + 1, hi)
merge(a, lo, mid, hi)
def sort_array(a):
return sort(a, 0, len(a) - 1)
def is_sorted(a):
i = 1
while i < len(a):
if less(a[i], a[i-1]):
return False
i += 1
return True
if __name__ == '__main__':
a = stdin_to_ints(sys.stdin)
print 'Array before:'
print a
sort_array(a)
print 'Array after:'
print a
print is_sorted(a)