blob: 8d0b5733f23f4b4f758d314749bac4229d52678c (
plain) (
blame)
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
|
# Copyright 2015 Egor Tensin <Egor.Tensin@gmail.com>
# This file is licensed under the terms of the MIT License.
# See LICENSE.txt for details.
import sys
from ..algorithm import SortingAlgorithm
def merge(left, right):
result = []
l, r = 0, 0
while l < len(left) and r < len(right):
if left[l] <= right[r]:
result.append(left[l])
l += 1
else:
result.append(right[r])
r += 1
if left:
result.extend(left[l:])
if right:
result.extend(right[r:])
return result
def merge_sort(xs):
if len(xs) < 2:
return xs
mid = len(xs) // 2
return merge(merge_sort(xs[:mid]), merge_sort(xs[mid:]))
_ALGORITHMS = [
SortingAlgorithm('merge_sort', 'Merge sort', merge_sort),
]
def _parse_args(args=sys.argv):
return list(map(int, args[1:]))
def main(args=sys.argv):
xs = _parse_args(args)
print(merge_sort(list(xs)))
if __name__ == '__main__':
main()
|