Advertisement
kevinbocky

mergesort.py

Jan 28th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. # define a mergesort function
  2.  
  3. def merge(list1, list2):
  4. list3 = []
  5. while len(list1) > 0 and len(list2) > 0:
  6. if list1[0] < list2[0]:
  7. list3.append(list1.pop(0))
  8. else:
  9. list3.append(list2.pop(0))
  10. if list1 == []:
  11. list3 += list2
  12. else:
  13. list3 += list1
  14. print("merged list is", list3)
  15. return list3
  16.  
  17.  
  18. def merge_sort(unsorted):
  19. if len(unsorted) < 2:
  20. return unsorted
  21. else:
  22. middle = len(unsorted) // 2
  23. front = unsorted[:middle]
  24. back = unsorted[middle:]
  25. print("splits are", front, back)
  26. front = merge_sort(front)
  27. back = merge_sort(back)
  28. return merge(front, back)
  29.  
  30.  
  31. my_list = [5,4,3,2,1]
  32. merge_sort(my_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement