Source

sorting_network / sorting_net.py

comparator = lambda x, y : (min(x, y), max(x, y))
comparate  = lambda l, r : [comparator(*x) for x in zip(l, r)]
separate   = lambda s    : (s[:len(s)//2], s[len(s)//2:])

def half_cleaner(seq, merge = True):
    if len(seq) == 1:
        return seq
    left, right = separate(seq)
    left, right = map(list, zip(*comparate(left, right)))
    return (left + right) if merge else (left, right)

def bitonic_sorter(seq):
    if len(seq) <= 1:
        return seq
    left, right = half_cleaner(seq, False)
    return bitonic_sorter(left) + bitonic_sorter(right)

def merger(seq):
    left, right = separate(seq)
    left, right = zip(*comparate(left, reversed(right)))
    return bitonic_sorter(left) + bitonic_sorter(right)

def sorter(seq):
    if len(seq) == 1:
        return seq
    if len(seq) == 2:
        return list(comparator(*seq))
    left, right = separate(seq)
    return merger(sorter(left) + sorter(right))