有序序列的合并,python实现。

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
#coding:utf-8

a = [2,4,6,8,10]
b = [3,5,7,9,11,13,15]
c = []

def merge(a,b):
i,j = 0,0
while i<=len(a)-1 and j<=len(b)-1:
if a[i]<b[j]:
c.append(a[i])
i+=1
else:
c.append(b[j])
j+=1
if i<=len(a)-1:
for m in a[i:]:
c.append(m)

if j<=len(b)-1:
for n in b[j:]:
c.append(n)
print(c)

merge(a,b)

运行结果为:

1
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15]


打开微信扫一扫,关注微信公众号【搜索与推荐Wiki】