@@ -29,36 +29,20 @@ def merge_sort(collection):
2929 >>> merge_sort([-2, -5, -45])
3030 [-45, -5, -2]
3131 """
32- length = len (collection )
33- if length > 1 :
34- midpoint = length // 2
35- left_half = merge_sort (collection [:midpoint ])
36- right_half = merge_sort (collection [midpoint :])
37- i = 0
38- j = 0
39- k = 0
40- left_length = len (left_half )
41- right_length = len (right_half )
42- while i < left_length and j < right_length :
43- if left_half [i ] < right_half [j ]:
44- collection [k ] = left_half [i ]
45- i += 1
46- else :
47- collection [k ] = right_half [j ]
48- j += 1
49- k += 1
50-
51- while i < left_length :
52- collection [k ] = left_half [i ]
53- i += 1
54- k += 1
55-
56- while j < right_length :
57- collection [k ] = right_half [j ]
58- j += 1
59- k += 1
60-
61- return collection
32+ def merge (left , right ):
33+ '''merge left and right
34+ :param left: left collection
35+ :param right: right collection
36+ :return: merge result
37+ '''
38+ result = []
39+ while left and right :
40+ result .append (left .pop (0 ) if left [0 ] <= right [0 ] else right .pop (0 ))
41+ return result + left + right
42+ if len (collection ) <= 1 :
43+ return collection
44+ mid = len (collection ) // 2
45+ return merge (merge_sort (collection [:mid ]), merge_sort (collection [mid :]))
6246
6347
6448if __name__ == '__main__' :
@@ -69,4 +53,4 @@ def merge_sort(collection):
6953
7054 user_input = raw_input ('Enter numbers separated by a comma:\n ' ).strip ()
7155 unsorted = [int (item ) for item in user_input .split (',' )]
72- print (merge_sort (unsorted ))
56+ print (* merge_sort (unsorted ), sep = ',' )
0 commit comments