Design an efficient algorithm to sort 5 distinct keys in fewer than 8 comparisons

前端 未结 13 1389
轮回少年
轮回少年 2020-12-01 11:30

Design an efficient algorithm to sort 5 distinct - very large - keys less than 8 comparisons in the worst case. You can\'t use radix sort.

13条回答
  •  醉酒成梦
    2020-12-01 11:35

    FWIW, here's a compact and easy to follow Python version with tests to make sure it works:

    def sort5(a, b, c, d, e):
        'Sort 5 values with 7 Comparisons'
        if a < b:      a, b = b, a
        if c < d:      c, d = d, c
        if a < c:      a, b, c, d = c, d, a, b
        if e < c:
            if e < d:  pass
            else:      d, e = e, d
        else:
            if e < a:  c, d, e = e, c, d
            else:      a, c, d, e = e, a, c, d
        if b < d:
            if b < e:  return b, e, d, c, a
            else:      return e, b, d, c, a
        else:
            if b < c:  return e, d, b, c, a
            else:      return e, d, c, b, a
    
    if __name__ == '__main__':
        from itertools import permutations
    
        assert all(list(sort5(*p)) == sorted(p) for p in permutations(range(5)))
    

提交回复
热议问题