Advertisement
KaeruCT

Untitled

Aug 12th, 2012
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. #!/usr/bin/env python2
  2.  
  3. numlist = [0, 2, 4, 1, -5, 4, 1, 5, 49, 24, 13, -50, 40, -24, 44, 9]
  4.  
  5. def merge (left, right, cmp_function):
  6.     list = []
  7.  
  8.     # while either list has elements
  9.     while len(left) > 0 or len(right) > 0:
  10.  
  11.         # if both lists have elements, do the comparison to see which goes first
  12.         if len(left) > 0 and len(right) > 0:
  13.             if cmp_function(left[0], right[0]):
  14.                 list.append(left.pop(0))
  15.             else:
  16.                 list.append(right.pop(0))
  17.  
  18.         # if only one list has elements, push them into the result list
  19.         elif len(left) > 0:
  20.             list.append(left.pop(0))
  21.  
  22.         elif len(right) > 0:
  23.             list.append(right.pop(0))
  24.  
  25.     return list
  26.  
  27. def merge_sort (list, cmp_function):
  28.     length = len(list)
  29.  
  30.     # if the list has only one element, it's already sorted
  31.     if length == 1:
  32.         return list
  33.  
  34.     middle = (length + 1) / 2
  35.  
  36.     # divide list in two, by the middle
  37.     left, right = [list[i:i+middle] for i in range(0, len(list), middle)]
  38.  
  39.     # merge sort left and right parts
  40.     left = merge_sort(left, cmp_function)
  41.     right = merge_sort(right, cmp_function)
  42.  
  43.     # merge left and right into one list
  44.     return merge(left, right, cmp_function)
  45.  
  46. print merge_sort(numlist, lambda a, b: a > b)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement