本文实例讲述了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 #合并数据 test1 = [ 1 , 2 , 5 , 7 , 9 ] test2 = [ 2 , 4 , 6 , 8 , 10 , 11 , 34 , 55 ] def mergetest(test1,test2): result = [] len1 = len (test1) len2 = len (test2) i = 0 j = 0 while i<len1 and j<len2: if test1[i]< = test2[j]: result.append(test1[i]) i + = 1 else : result.append(test2[j]) j + = 1 if i<len1: for z in range (i + 1 ,len1): result.append(test1[z]) elif j<len2: for z in range (j + 1 ,len2): result.append(test2[z]) return result print mergetest(test1,test2) |
运行结果:
[1, 2, 2, 4, 5, 6, 7, 8, 9, 11, 34, 55]
add:链表情况下合并
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
def merge_link(link1,link2): head = single_link( 0 ) first = head while link1! = None and link2! = None : if l1.val< = l2.val: head. next = l1 l1 = l1. next else : head. next = l2 l2 = l2. next head = head. next if l1! = None : head. next = l1 elif l2! = None : head. next = lw return first. next |
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/qq_30758629/article/details/80965825