Merge two sorted arrays in Python using heapq
Given two sorted arrays, the task is to merge them in a sorted manner.
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.
[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:
- heapq.heappush(heap,item) : Push the value item onto the heap, maintaining the heap invariant.
- heapq.heappop(heap) : Pop and return the smallest item from the heap, maintaining the heap invariant. If the heap is empty, IndexError is raised. To access the smallest item without popping it, use heap.
- heapq.heappushpop(heap, item) : Push item on the heap, then pop and return the smallest item from the heap. The combined action runs more efficiently than heappush() followed by a separate call to heappop().
- heapq.heapify(x) : Transform list x into a heap, in-place, in linear time.
- heapq.merge(*iterables) : Merge multiple sorted inputs into a single sorted output (for example, merge timestamped entries from multiple log files). Returns an iterator over the sorted values.
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.My Personal Notes arrow_drop_up