Advertisement
B1KMusic

Demonstration of two-tier sorting using comparators

Sep 8th, 2018
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.54 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. # https://repl.it/@BradenBest/ProbableJuvenileRegisters
  3.  
  4. # Defining a general-purpose sort function (selection sort algorithm)
  5. # function takes a list and an optional comparator
  6.  
  7. def cmp_default(a, b):
  8.     """General purpose comparator. Works for numbers and strings"""
  9.     if(a < b): return -1
  10.     if(a > b): return 1
  11.     return 0
  12.  
  13. def swap(array, a, b):
  14.     temp = array[a]
  15.     array[a] = array[b]
  16.     array[b] = temp
  17.  
  18. def sort_run(array, start, cmp):
  19.     """find the lowest item and swap it with the start point"""
  20.     lowest = start
  21.  
  22.     for i in xrange(start, len(array)):
  23.         if cmp(array[lowest], array[i]) > 0:
  24.             lowest = i
  25.  
  26.     if lowest != start:
  27.         swap(array, start, lowest)
  28.  
  29. def sort(array, cmp = cmp_default):
  30.     for i in xrange(len(array)):
  31.         sort_run(array, i, cmp)
  32.  
  33. # Testing our sort function
  34.  
  35. def cmp_flight(a, b):
  36.     """Sort by destination first, arrival time second"""
  37.     cmpr = cmp_default(a[0], b[0])
  38.  
  39.     if cmpr == 0:
  40.         return cmp_default(a[1], b[1])
  41.  
  42.     return cmpr
  43.  
  44. def before_and_after(lst, cmp = None):
  45.     print "Before: %s" % str(lst)
  46.  
  47.     if cmp is None:
  48.         sort(lst)
  49.     else:
  50.         sort(lst, cmp)
  51.  
  52.     print "After:  %s\n" % str(lst)
  53.  
  54. list1 = [1,5,32,6,7,2,7,34,6,8,34,9,5,1,454,2]
  55. list2 = ["Alice", "Xander", "Jerry", "Bob", "Bobert", "Ian"]
  56. list3 = [["Chicago", 1045], ["Birmingham", 630], ["Chicago", 700], ["Birmingham", 845]]
  57.  
  58. before_and_after(list1)
  59. before_and_after(list2)
  60. before_and_after(list3, cmp_flight)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement