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

 Live Demo

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]

Updated on: 28-Apr-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements