Program to merge two sorted list to form larger sorted list in Python

PythonServer Side ProgrammingProgramming

Suppose we have two sorted lists A and B. We have to merge them and form only one sorted list 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]

We will solve this using recursion. So the function will work like below −

  • x:= a new list
  • i:= 0, j:= 0
  • while i < size of (lst0) and j < size of (lst1), do
    • if lst0[i] > lst1[j], then
      • insert lst1[j] at the end of x
      • j:= j+1
    • otherwise when lst0[i]<lst1[j], then
      • insert lst0[i] at the end of x
      • i:= i+1
    • otherwise,
      • insert lst0[i] at the end of x
      • insert lst1[j] at the end of x
      • i:= i+1, j:= j+1
  • while i<len(lst0), do
    • insert lst0[i] at the end of x
    • i:= i+1
  • while j<len(lst1), do
    • insert lst1[j] at the end of x
    • j:= j+1
  • return x

Let us see the implementation to get better understanding

Example

 Live Demo

class Solution:
   def solve(self, lst0, lst1):
      x=[]
      i=0
      j=0
      while(i<len(lst0) and j<len(lst1)):
         if(lst0[i]>lst1[j]):
            x.append(lst1[j])
            j=j+1
         elif(lst0[i]<lst1[j]):
            x.append(lst0[i])
            i=i+1
         else:
            x.append(lst0[i])
            x.append(lst1[j])
            i=i+1
            j=j+1
      while(i<len(lst0)):
         x.append(lst0[i])
         i=i+1
      while(j<len(lst1)):
         x.append(lst1[j])
         j=j+1
      return x
ob = Solution()
print(ob.solve([1,2,4,7], [1,3,4,5,6,8]))

Input

[1,2,4,7], [1,3,4,5,6,8]

Output

[1, 1, 2, 3, 4, 4, 5, 6, 7, 8]
raja
Published on 06-Oct-2020 06:30:51
Advertisements