归并排序算法-python实现

时间:2022-04-10 10:14:12
 1 #-*- coding: UTF-8 -*-
 2 import numpy as np
 3 
 4 def Merge(a, f, m, l):
 5     i = f
 6     j = m + 1
 7     tmp = []
 8     while i <= m and j <= l:
 9         if a[i] <= a[j]:
10             tmp.append(a[i])
11             i += 1
12         else:
13             tmp.append(a[j])
14             j += 1
15 
16     while i <= m:
17         tmp.append(a[i])
18         i += 1
19     while j<= l:
20         tmp.append(a[j])
21         j+= 1
22     i = f
23     for x in xrange(0, len(tmp)):
24         a[i] = tmp[x]
25         i += 1
26 
27 def MergeSort(a, f, l):
28     if f< l:
29         m = (l + f) / 2
30         MergeSort(a, f, m)
31         MergeSort(a, m+1, l)
32         Merge(a, f, m, l)
33 
34 if __name__ == '__main__':
35     a = np.random.randint(0, 10, size = 10)
36     print "Before sorting..."
37     print "---------------------------------------------------------------"
38     print a
39     print "---------------------------------------------------------------"
40     MergeSort(a, 0, a.size-1)
41     print "After sorting..."
42     print "---------------------------------------------------------------"
43     print a
44     print "---------------------------------------------------------------"