Merge two sorted arrays in Python using heapq?

PythonProgrammingServer Side Programming

In this section we will see how two sorted lists can be merged using the heapq module in Python. As an example, if list1 = [10, 20, 30, 40] and list2 = [100, 200, 300, 400, 500], then after merging it will return list3 = [10, 20, 30, 40, 100, 200, 300, 400, 500]

To perform this task, we will use the heapq module. This module comes with Python as Standard Library Module. So we need to import it before using it.

import heapq

The heapq module has some properties. These are like below −

Method heapq.heapify(iterable)

It is used to convert an iterable dataset to heap data structure.

Method heapq.heappush(heap, element)

This method is used to insert the element into the heap. After that re-heap the entire heap structure.

Method heapq.heappop(heap)

This method is used to return and delete the element from the top of the heap and perform heapify on the rest of the elements.

Method heapq.heappushpop(heap, element)

This method is used to insert and pop element in one statement.

Method heapq.heapreplace(heap, element)

This method is used to insert and pop element in one statement. It removes the element from root of the heap, then insert element into the heap.

Method heapq.nlargest(n, iterable, key=None)

This method is used to return n largest element from the heap.

Method heapq.nsmallest(n, iterable, key=None)

This method is used to return n smallest element from the heap.

Example code

 Live Demo

import heapq
first_list = [45, 12, 63, 95, 74, 21, 20, 15, 36]
second_list = [42, 13, 69, 54, 15]

first_list = sorted(first_list)
second_list = sorted(second_list)

print('First sorted list: ' + str(first_list))
print('Second sorted list: ' + str(second_list))

final_list = list(heapq.merge(first_list, second_list))
print('The final list: ' + str(final_list))

Output

First sorted list: [12, 15, 20, 21, 36, 45, 63, 74, 95]
Second sorted list: [13, 15, 42, 54, 69]
The final list: [12, 13, 15, 15, 20, 21, 36, 42, 45, 54, 63, 69, 74, 95]
raja
Published on 14-Nov-2018 12:36:16
Advertisements