Advertisement
DarkPotatoKing

merge_sort.py

Oct 8th, 2014
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. '''
  2. Kyle C. Rosales (DarkPotatoKing)
  3. October 8, 2014
  4. Merge Sort
  5. '''
  6.  
  7. def merge_sort(ls):
  8.  
  9.     def insertion_sort(ls):
  10.         if len(ls) <= 1: return ls
  11.         for i in xrange(1, len(ls)):
  12.             j = i
  13.             while j > 0 and ls[j-1] > ls[j]:
  14.                 ls[j-1], ls[j] = ls[j], ls[j-1]
  15.                 j -= 1
  16.         return ls
  17.  
  18.     def merge_lists(list1, list2):
  19.         temp = []
  20.         while len(list1) > 0 or len(list2) > 0:
  21.             if len(list1) == 0:
  22.                 while len(list2) > 0:
  23.                     temp.append(list2.pop(0))
  24.             elif len(list2) == 0:
  25.                 while len(list1) > 0:
  26.                     temp.append(list1.pop(0))
  27.             elif list1[0] < list2[0]: temp.append(list1.pop(0))
  28.             else: temp.append(list2.pop(0))
  29.         return temp
  30.  
  31.     #OPTIMIZATION: Switch to insertion sort for small data sets.
  32.     if len(ls) <= 4:
  33.         return insertion_sort(ls)
  34.    
  35.     mid = len(ls) / 2
  36.     left_partition = ls[0:mid]
  37.     right_partition = ls[mid:len(ls)]
  38.    
  39.     left_partition =  merge_sort(left_partition)
  40.     right_partition =  merge_sort(right_partition)
  41.    
  42.     return merge_lists(left_partition, right_partition)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement