Advertisement
STANAANDREY

mergesort py

Oct 22nd, 2022 (edited)
928
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.76 KB | None | 0 0
  1. def merge(lst1, lst2):
  2.     if len(lst1) == 0:
  3.         return lst2
  4.     if len(lst2) == 0:
  5.         return lst1
  6.  
  7.     if lst1[0] > lst2[0]:
  8.         return [lst2[0]] + merge(lst1, lst2[1:])
  9.     else:
  10.         return [lst1[0]] + merge(lst1[1:], lst2)
  11.  
  12.  
  13. def split(lst):
  14.     if len(lst) == 0:
  15.         return [], []
  16.  
  17.     lst1, lst2 = split(lst[2:])
  18.  
  19.     lst1.insert(0, lst[0])
  20.     if len(lst) >= 2:
  21.         lst2.insert(0, lst[1])
  22.  
  23.     return lst1, lst2
  24.  
  25.  
  26. def mergeSort(lst):
  27.     if len(lst) == 1:
  28.         return lst
  29.  
  30.     pair = split(lst)
  31.     sortedLeft = mergeSort(pair[0])
  32.     sortedRight = mergeSort(pair[1])
  33.     return merge(sortedLeft, sortedRight)
  34.  
  35.  
  36. lst1 = [int(item) for item in input("Enter the list items : ").split()]
  37. print(mergeSort(lst1))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement