Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Merge two sorted arrays in Python using heapq?
The heapq module in Python provides an efficient way to merge multiple sorted iterables into a single sorted sequence. The heapq.merge() function is specifically designed for merging sorted arrays while maintaining the sorted order.
The heapq.merge() Function
The heapq.merge() function accepts multiple sorted iterables and returns an iterator that produces elements in sorted order. It uses a min-heap internally to efficiently merge the arrays without loading everything into memory at once.
Syntax
heapq.merge(*iterables, key=None, reverse=False)
Basic Example
Here's how to merge two sorted arrays using heapq.merge() ?
import heapq
list1 = [10, 20, 30, 40]
list2 = [100, 200, 300, 400, 500]
merged = list(heapq.merge(list1, list2))
print("Merged array:", merged)
Merged array: [10, 20, 30, 40, 100, 200, 300, 400, 500]
Merging Unsorted Arrays
If your arrays are not sorted, you need to sort them first before using heapq.merge() ?
import heapq
first_list = [45, 12, 63, 95, 74, 21, 20, 15, 36]
second_list = [42, 13, 69, 54, 15]
# Sort both lists first
first_list = sorted(first_list)
second_list = sorted(second_list)
print("First sorted list:", first_list)
print("Second sorted list:", second_list)
# Merge the sorted lists
final_list = list(heapq.merge(first_list, second_list))
print("The final merged list:", final_list)
First sorted list: [12, 15, 20, 21, 36, 45, 63, 74, 95] Second sorted list: [13, 15, 42, 54, 69] The final merged list: [12, 13, 15, 15, 20, 21, 36, 42, 45, 54, 63, 69, 74, 95]
Merging Multiple Arrays
You can merge more than two arrays at once ?
import heapq
arr1 = [1, 5, 9]
arr2 = [2, 6, 10]
arr3 = [3, 7, 11]
merged = list(heapq.merge(arr1, arr2, arr3))
print("Merged result:", merged)
Merged result: [1, 2, 3, 5, 6, 7, 9, 10, 11]
Key Advantages
- Memory Efficient: Returns an iterator, processes elements on-demand
- Time Complexity: O(n log k) where n is total elements and k is number of arrays
- Stable Sort: Maintains relative order of equal elements
- Multiple Inputs: Can merge any number of sorted iterables
Comparison with Alternative Methods
| Method | Time Complexity | Space Complexity | Memory Efficient |
|---|---|---|---|
heapq.merge() |
O(n log k) | O(k) | Yes (iterator) |
| Concatenate + Sort | O(n log n) | O(n) | No |
| Manual merge | O(n) | O(n) | No |
Conclusion
The heapq.merge() function is the most efficient way to merge sorted arrays in Python. It provides optimal time complexity and memory usage, making it ideal for large datasets or when working with multiple sorted sequences.
