Python3 Program for Merge 3 Sorted Arrays
Last Updated :
05 Sep, 2024
Given 3 arrays (A, B, C) which are sorted in ascending order, we are required to merge them together in ascending order and output the array D.
Examples:
Input : A = [1, 2, 3, 4, 5]
B = [2, 3, 4]
C = [4, 5, 6, 7]
Output : D = [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 7]
Input : A = [1, 2, 3, 5]
B = [6, 7, 8, 9 ]
C = [10, 11, 12]
Output: D = [1, 2, 3, 5, 6, 7, 8, 9. 10, 11, 12]
Method 1 (Two Arrays at a time)
We have discussed at Merging 2 Sorted arrays . So we can first merge two arrays and then merge the resultant with the third array. Time Complexity for merging two arrays O(m+n). So for merging the third array, the time complexity will become O(m+n+o). Note that this is indeed the best time complexity that can be achieved for this problem.
Space Complexity: Since we merge two arrays at a time, we need another array to store the result of the first merge. This raises the space complexity to O(m+n). Note that space required to hold the result of 3 arrays is ignored while calculating complexity.
Algorithm
function merge(A, B)
Let m and n be the sizes of A and B
Let D be the array to store result
// Merge by taking smaller element from A and B
while i < m and j < n
if A[i] <= B[j]
Add A[i] to D and increment i by 1
else Add B[j] to D and increment j by 1
// If array A has exhausted, put elements from B
while j < n
Add B[j] to D and increment j by 1
// If array B has exhausted, put elements from A
while i < n
Add A[j] to D and increment i by 1
Return D
function merge_three(A, B, C)
T = merge(A, B)
return merge(T, C)
The Implementations are given below
Python
# Python program to merge three sorted arrays
# by merging two at a time.
def merge_two(a, b):
(m, n) = (len(a), len(b))
i = j = 0
# Destination Array
d = []
# Merge from a and b together
while i < m and j < n:
if a[i] <= b[j]:
d.append(a[i])
i += 1
else:
d.append(b[j])
j += 1
# Merge from a if b has run out
while i < m:
d.append(a[i])
i += 1
# Merge from b if a has run out
while j < n:
d.append(b[j])
j += 1
return d
def merge(a, b, c):
t = merge_two(a, b)
return merge_two(t, c)
if __name__ == "__main__":
A = [1, 2, 3, 5]
B = [6, 7, 8, 9]
C = [10, 11, 12]
print(merge(A, B, C))
Output[1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12]
Method 2 (Three arrays at a time)
The Space complexity of method 1 can be improved we merge the three arrays together.
function merge-three(A, B, C)
Let m, n, o be size of A, B, and C
Let D be the array to store the result
// Merge three arrays at the same time
while i < m and j < n and k < o
Get minimum of A[i], B[j], C[i]
if the minimum is from A, add it to
D and advance i
else if the minimum is from B add it
to D and advance j
else if the minimum is from C add it
to D and advance k
// After above step at least 1 array has
// exhausted. Only C has exhausted
while i < m and j < n
put minimum of A[i] and B[j] into D
Advance i if minimum is from A else advance j
// Only B has exhausted
while i < m and k < o
Put minimum of A[i] and C[k] into D
Advance i if minimum is from A else advance k
// Only A has exhausted
while j < n and k < o
Put minimum of B[j] and C[k] into D
Advance j if minimum is from B else advance k
// After above steps at least 2 arrays have
// exhausted
if A and B have exhausted take elements from C
if B and C have exhausted take elements from A
if A and C have exhausted take elements from B
return D
Complexity: The Time Complexity is O(m+n+o) since we process each element from the three arrays once. We only need one array to store the result of merging and so ignoring this array, the space complexity is O(1).
Implementation of the algorithm is given below:
Python
# Python program to merge three sorted arrays
# simultaneously.
def merge_three(a, b, c):
(m, n, o) = (len(a), len(b), len(c))
i = j = k = 0
# Destination array
d = []
while i < m and j < n and k < o:
# Get Minimum element
m = min(a[i], b[j], c[k])
# Add m to D
d.append(m)
# Increment the source pointer which
# gives m
if a[i] == m:
i += 1
elif b[j] == m:
j += 1
elif c[k] == m:
k += 1
# Merge a and b in c has exhausted
while i < m and j < n:
if a[i] <= b[k]:
d.append(a[i])
i += 1
else:
d.append(b[j])
j += 1
# Merge b and c if a has exhausted
while j < n and k < o:
if b[j] <= c[k]:
d.append(b[j])
j += 1
else:
d.append(c[k])
k += 1
# Merge a and c if b has exhausted
while i < m and k < o:
if a[i] <= c[k]:
d.append(a[i])
i += 1
else:
d.append(c[k])
k += 1
# Take elements from a if b and c
# have exhausted
while i < m:
d.append(a[i])
i += 1
# Take elements from b if a and c
# have exhausted
while j < n:
d.append(b[j])
j += 1
# Take elements from c if a and
# b have exhausted
while k < o:
d.append(c[k])
k += 1
return d
if __name__ == "__main__":
a = [1, 2, 41, 52, 84]
b = [1, 2, 41, 52, 67]
c = [1, 2, 41, 52, 67, 85]
print(merge_three(a, b, c))
Output[1, 1, 1, 2, 2, 41, 41, 52, 52, 67, 67, 85]
Note: While it is relatively easy to implement direct procedures to merge two or three arrays, the process becomes cumbersome if we want to merge 4 or more arrays. In such cases, we should follow the procedure shown in Merge K Sorted Arrays .
Another Approach (Without caring about the exhausting array):
The code written above can be shortened by the below code. Here we do not need to write code if any array gets exhausted.
Below is the implementation of the above approach:
Python
# Python program to merge three sorted arrays
# Without caring about the exhausting array
# import the module
import sys
# A[], B[], C[]: input arrays
# Function to merge three sorted lists into a single
# list.
def merge3sorted(A, B, C):
ans = []
l1 = len(A)
l2 = len(B)
l3 = len(C)
i, j, k = 0, 0, 0
while(i < l1 or j < l2 or k < l3):
# Assigning a, b, c with max values so that if
# any value is not present then also we can sort
# the array.
a = sys.maxsize
b = sys.maxsize
c = sys.maxsize
# a, b, c variables are assigned only if the
# value exist in the array.
if(i < l1):
a = A[i]
if(j < l2):
b = B[j]
if(k < l3):
c = C[k]
# Checking if 'a' is the minimum
if(a <= b and a <= c):
ans.append(a)
i = i+1
# Checking if 'b' is the minimum
if(b <= a and b <= c):
ans.append(b)
j = j+1
# Checking if 'c' is the minimum
if(c <= a and c <= b):
ans.append(c)
k = k+1
return ans
def printeSorted(List):
for x in List:
print(x, end=" ")
# Driver program to test above functions
A = [1, 2, 41, 52, 84]
B = [1, 2, 41, 52, 67]
C = [1, 2, 41, 52, 67, 85]
final_ans = merge3sorted(A, B, C)
printeSorted(final_ans)
# This code is contributed by Pushpesh Raj
Time Complexity: O(m+n+o) where m, n, o are the lengths of the 1st, 2nd, and 3rd arrays.
Space Complexity: O(m+n+o) where m, n, o are the lengths of the 1st, 2nd, and 3rd arrays. Space used for the output array.
Please refer complete article on Merge 3 Sorted Arrays for more details!
Similar Reads
Python Program to Merge Mails
In this article, we are going to merge mails with Python Python Program to Merge MailsTo merge two or more mail files in Python, the below following steps have to be followed: To execute the program, firstly we require two .txt files 'mail1.txt' and 'mail2.txt' where both of the .txt files will cont
2 min read
Python Program For Merge Sort For Doubly Linked List
Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked l
3 min read
Python Program To Merge Two Sorted Lists (In-Place)
Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).Examples: Input: head1: 5->7->9 head2: 4->6->8 Output: 4->5->6->7->8->9 Explanation: The output list is in sorted order. Input: head1: 1->3->5->7 head2: 2->4 Output: 1->2->3->4->5->7 Explanation: T
5 min read
Python Program For Merge Sort Of Linked Lists
Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible. Let the head be the first node of the linked list to be sorted and headRe
6 min read
Python Program For Sorting An Array Of 0s, 1s and 2s
Given an array A[] consisting 0s, 1s and 2s. The task is to write a function that sorts the given array. The functions should put all 0s first, then all 1s and all 2s in last.Examples: Input: {0, 1, 2, 0, 1, 2} Output: {0, 0, 1, 1, 2, 2} Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1} Output: {0, 0, 0,
5 min read
Python program to print sorted number formed by merging all elements in array
Given an array arr[], the task is to combine all the elements in the array sequentially and sort the digits of this number in ascending order. Note: Ignore leading zeros. Examples: Input: arr =[7, 845, 69, 60]Output: 4566789Explanation: The number formed by combining all the elements is "78456960" a
4 min read
Python Program To Merge K Sorted Linked Lists - Set 1
Given K sorted linked lists of size N each, merge them and print the sorted output. Examples: Input: k = 3, n = 4 list1 = 1->3->5->7->NULL list2 = 2->4->6->8->NULL list3 = 0->9->10->11->NULL Output: 0->1->2->3->4->5->6->7->8->9->10-
6 min read
Python3 Program for Maximize elements using another array
Given two arrays with size n, maximize the first array by using the elements from the second array such that the new array formed contains n greatest but unique elements of both the arrays giving the second array priority (All elements of second array appear before first array). The order of appeara
4 min read
Python3 Program to Print all triplets in sorted array that form AP
Given a sorted array of distinct positive integers, print all triplets that form AP (or Arithmetic Progression)Examples : Input : arr[] = { 2, 6, 9, 12, 17, 22, 31, 32, 35, 42 };Output :6 9 122 12 2212 17 222 17 3212 22 329 22 352 22 4222 32 42Input : arr[] = { 3, 5, 6, 7, 8, 10, 12};Output :3 5 75
3 min read
Python3 Program for Shortest Un-ordered Subarray
An array is given of n length, and problem is that we have to find the length of shortest unordered {neither increasing nor decreasing} sub array in given array.Examples: Input : n = 5 7 9 10 8 11Output : 3Explanation : 9 10 8 unordered sub array.Input : n = 5 1 2 3 4 5Output : 0 Explanation : Array
2 min read