Skip to content

Commit 28370ed

Browse files
authored
Create merge_sorted_lists.py
1 parent e073dac commit 28370ed

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

merge_sorted_lists.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
2+
##merge two sorted lists and return
3+
##input [1,2,5,20], [4,6,7,8]
4+
##output: [1,2,4,5,6,7,8,20]
5+
##
6+
7+
def merge_lists(l1,l2):
8+
9+
## take indexes to both arrays
10+
## compare them ....
11+
### if equal just copy
12+
## if list1 is greater increment index of list 2
13+
## and vice versa
14+
15+
sorted_list = []
16+
while (l1 and l2):
17+
if (l1[0] <= l2[0]): # Compare both heads
18+
item = l1.pop(0) # Pop from the head
19+
sorted_list.append(item)
20+
else:
21+
item = l2.pop(0)
22+
sorted_list.append(item)
23+
24+
sorted_list.extend(l1 if l1 else l2)
25+
return sorted_list
26+
27+
print(merge_lists([1,2,20], [4,6,7,8]))

0 commit comments

Comments
 (0)