| 1 | #!/usr/bin/env python2
|
| 2 | """
|
| 3 | bubble_sort.py
|
| 4 | """
|
| 5 | from __future__ import print_function
|
| 6 |
|
| 7 | import sys
|
| 8 |
|
| 9 |
|
| 10 | # https://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort#Python
|
| 11 | def bubble_sort_int(seq):
|
| 12 | """Inefficiently sort the mutable sequence (list) in place.
|
| 13 | seq MUST BE A MUTABLE SEQUENCE.
|
| 14 |
|
| 15 | As with list.sort() and random.shuffle this does NOT return
|
| 16 | """
|
| 17 | changed = True
|
| 18 | while changed:
|
| 19 | changed = False
|
| 20 | for i in xrange(len(seq) - 1):
|
| 21 | # fairer comparison against shell, which doesn't have integers
|
| 22 | if int(seq[i]) > int(seq[i+1]):
|
| 23 | seq[i], seq[i+1] = seq[i+1], seq[i]
|
| 24 | changed = True
|
| 25 |
|
| 26 |
|
| 27 | def bubble_sort_bytes(seq):
|
| 28 | """
|
| 29 | Sort with lexiographical comparison.
|
| 30 | """
|
| 31 | changed = True
|
| 32 | while changed:
|
| 33 | changed = False
|
| 34 | for i in xrange(len(seq) - 1):
|
| 35 | if seq[i] > seq[i+1]:
|
| 36 | seq[i], seq[i+1] = seq[i+1], seq[i]
|
| 37 | changed = True
|
| 38 |
|
| 39 |
|
| 40 | def main(argv):
|
| 41 | lines = sys.stdin.readlines()
|
| 42 |
|
| 43 | if argv[1] == 'int':
|
| 44 | bubble_sort_int(lines)
|
| 45 | else:
|
| 46 | bubble_sort_bytes(lines)
|
| 47 |
|
| 48 | for line in lines:
|
| 49 | sys.stdout.write(line)
|
| 50 |
|
| 51 |
|
| 52 | if __name__ == '__main__':
|
| 53 | try:
|
| 54 | main(sys.argv)
|
| 55 | except RuntimeError as e:
|
| 56 | print('FATAL: %s' % e, file=sys.stderr)
|
| 57 | sys.exit(1)
|