Examples:
Input: arr1 = [1, 3, 4, 5] arr2 = [2, 4, 6, 8] Output: arr3 = [1, 2, 3, 4, 4 , 5, 6, 8] Input: arr1 = [5, 8, 9] arr2 = [4, 7, 8] Output: arr3 = [4, 5, 7, 8, 8, 9]
This problem has an existing solution, please refer to the link
# Function to combine two sorted arrays
from
heapq
import
merge
def
mergeArray (arr1, arr2):
return
list
(merge (arr1, arr2))
# Driver function
if
__ name__
=
=
"__ main __"
arr1
=
[
1
,
3
,
4
,
5
]
arr2
=
[
2
,
4
,
6
,
8
]
print
mergeArray (arr1, arr2)
Output:
[1, 2, 3, 4, 4, 5, 6, 8]
Module properties heapq?
This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.
To create a heap, use a list initialized with [], or you can convert a populated list to a heap using the heapify () function. The following functions are provided:
- heapq.heappush (heap, element): put the element values on the heap, maintaining the heap invariant.
- heapq.heappop (heap): take out and return the smallest element from the heap, maintaining the heap invariant. If the heap is empty, IndexError is promoted. To access the smallest item without opening it, use heap [0].
- heapq.heappushpop (heap, item): Click on an item on the heap, then pop and return the smallest item from the heap. The combined action is more efficient than heappush () followed by a separate call to heappop ().
- heapq.heapify (x): transform the list x into a heap in place in linear time.
- heapq.merge (* iterables): combine multiple sorted inputs into one sorted output (e.g. combine records with timestamps from multiple log files). Returns an iterator for sorted values.
This article courtesy of Shashank Mishra (Gullu) . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.
Please post comments if you find anything wrong or if you’d like to share more information on the topic discussed above.