abbarnes

Merge_Sort_Python2

Jan 21st, 2018
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.91 KB | None | 0 0
  1. # Functions to perform merge sort
  2. # Uses Python2
  3.  
  4. def merge(list1, list2):
  5.     """
  6.   Merge two sorted lists.
  7.  
  8.   Returns a new sorted list containing those elements that are in
  9.   either list1 or list2.
  10.  
  11.   This function can be iterative.
  12.   """  
  13.     merged = []
  14.     first = list(list1)
  15.     second = list(list2)
  16.     while len(merged) < len(list1) + len(list2) and first and second:
  17.         if first[0] < second[0]:
  18.             merged.append(first.pop(0))
  19.         else:
  20.             merged.append(second.pop(0))
  21.     merged += first
  22.     merged += second
  23.     return merged
  24.                
  25. def merge_sort(list1):
  26.     """
  27.   Sort the elements of list1.
  28.  
  29.   Return a new sorted list with the same elements as list1.
  30.  
  31.   This function should be recursive.
  32.   """
  33.     if len(list1) <= 1:
  34.         return list1
  35.     half = len(list1)/2
  36.     return merge(merge_sort(list1[0:half]), merge_sort(list1[half:]))
Advertisement
Add Comment
Please, Sign In to add comment