Advertisement
Guest User

Partition five elements by median in six comparisons

a guest
Jun 19th, 2012
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.53 KB | None | 0 0
  1. def medianSort(a, b, c, d, e):
  2.     if a > b: a, b = b, a
  3.     if d > e: d, e = e, d
  4.  
  5.     if a < d:
  6.         if b > c: b, c = c, b
  7.     else:
  8.         a, d = d, a
  9.         b, d = d, b
  10.         if c > e: c, e = e, c
  11.         c, d = d, c
  12.  
  13.     if b > d:
  14.         b, d = d, b
  15.         c, e = e, c
  16.  
  17.     if c > d: c, d = d, c
  18.  
  19.     return [a, b, c, d, e]
  20.  
  21. arr = [1, 2, 3, 4, 5]
  22.  
  23. from random import shuffle
  24.  
  25. for i in range(0, 1000):
  26.     shuffle(arr)
  27.     tmp = medianSort(arr[0], arr[1], arr[2], arr[3], arr[4])
  28.     assert(tmp[0] < tmp[2] and tmp[1] < tmp[2] and tmp[2] < tmp[3] and tmp[2] < tmp[4])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement