Advertisement
Iam_Sandeep

Merge sort

Sep 16th, 2021
1,021
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. #User function Template for python3
  2. https://practice.geeksforgeeks.org/problems/merge-sort/1
  3. class Solution:
  4.     def mergeSort(self,arr, l, r):
  5.         def use(arr):
  6.             if len(arr)<=1:
  7.                 return
  8.             mid=len(arr)//2
  9.             L=arr[:mid]
  10.             R=arr[mid:]
  11.             use(L)
  12.             use(R)
  13.             m,n=len(L),len(R)
  14.             i=j=k=0
  15.             while i<m and j<n:
  16.                 if L[i]<R[j]:
  17.                     arr[k]=L[i]
  18.                     i=i+1
  19.                 else:
  20.                     arr[k]=R[j]
  21.                     j=j+1
  22.                 k=k+1
  23.             while i<m:
  24.                 arr[k]=L[i]
  25.                 i=i+1
  26.                 k=k+1
  27.             while j<n:
  28.                 arr[k]=R[j]
  29.                 j=j+1
  30.                 k=k+1
  31.             return arr
  32.         return use(arr)
  33.  
  34.  
  35. #{
  36. #  Driver Code Starts
  37. #Initial Template for Python 3
  38.  
  39.  
  40.  
  41. if __name__ == "__main__":
  42.     t=int(input())
  43.     for i in range(t):
  44.         n=int(input())
  45.         arr=list(map(int,input().split()))
  46.         Solution().mergeSort(arr, 0, n-1)
  47.         for i in range(n):
  48.             print(arr[i],end=" ")
  49.         print()
  50. # } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement