
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Merge Sorted Array in Python
Suppose we have two sorted arrays A and B. We have to merge them and form only one sorted array C. The size of lists may different.
For an example, suppose A = [1,2,4,7] and B = [1,3,4,5,6,8], then merged list C will be [1,1,2,3,4,4,5,6,7,8]
To solve this, follow these steps −
- define i := 0, j := 0 and end := length of A – 1
- while end >= 0 and not A[end],
- end := end – 1
- while j < length of B
- if i > end and not A[i], then A[i] := B[j], and increase j by 1
- otherwise if A[i] > B[j], then perform shift(A, i), A[i] := B[j], increase end and j by 1
- increase i by 1
The shift method will work like below −
- take input num_arr, and i
- j := length of num_arr – 1
- while not num_arr [j] do j := j – 1
- while j >= i, do num_arr[j + 1] = num_arr[j], and j := j – 1
Let us see the implementation to get better understanding
Example
class Solution(object): def merge(self, nums1, m, nums2, n): i = 0 j = 0 end = len(nums1)-1 while end>=0 and not nums1[end]: end-=1 while j<len(nums2) : if i>end and not nums1[i]: nums1[i] = nums2[j] j+=1 elif nums1[i]>nums2[j]: self.shift(nums1,i) nums1[i] = nums2[j] end+=1 j+=1 i+=1 return nums1 def shift(self,num,i): j = len(num)-1 while not num[j]: j-=1 while j>=i: num[j+1] = num[j] j-=1 ob = Solution() print(ob.merge([1,2,3,0,0,0],3,[2,5,6],3))
Input
[1,2,3,0,0,0] [2,5,6]
Output
[1, 2, 2, 3, 5, 6]
- Related Articles
- Merge Two Sorted Lists in Python
- Merge k Sorted Lists in Python
- Merge two sorted arrays to form a resultant sorted array in JavaScript
- Merge two sorted arrays in Python using heapq?
- Program to merge K-sorted lists in Python
- Program to merge two sorted list to form larger sorted list in Python
- Merge two sorted arrays in Java
- Merge two sorted arrays in C#
- Merge k sorted arrays in Java
- Merge K sorted linked lists in Java
- Merge two sorted arrays using C++.
- Search in Rotated Sorted Array in Python
- Remove Duplicates from Sorted Array in Python
- Merge two sorted linked lists using C++.
- Search in Rotated Sorted Array II in Python

Advertisements