Merge two sorted arrays in Python using heapq

Given two sorted arrays, the task is to merge them in a sorted manner.

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 existing solution please refer Merge two sorted arrays link. We will solve this problem in python using heapq.merge() in a single line of code.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Function to merge 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)

chevron_right


Output:

[1, 2, 3, 4, 4, 5, 6, 8]

Properties of heapq module ?

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 to [], or you can transform a populated list into a heap via function heapify().The following functions are provided: