|
| 1 | +""" |
| 2 | +A practice implementation of bubble sort. |
| 3 | +""" |
| 4 | + |
| 5 | +def non_increasing(a, b): |
| 6 | + """ Returns true if the elements are in non-increasing order. """ |
| 7 | + return a >= b |
| 8 | + |
| 9 | +def non_decreasing(a, b): |
| 10 | + """ Returns true if the elements are in non-decreasing order. """ |
| 11 | + return a <= b |
| 12 | + |
| 13 | +def bubble_sort(input, compare=non_decreasing): |
| 14 | + """ |
| 15 | + The classic bubble sort algorithm. |
| 16 | +
|
| 17 | + Arguments: |
| 18 | + input -- the list of numbers to be sorted |
| 19 | +
|
| 20 | + Keyword Arguments: |
| 21 | + compare(a, b) -- function, returns true if the two elements are in order |
| 22 | +
|
| 23 | + >>> example = [9, 1, 4, 7, 2] |
| 24 | + >>> bubble_sort(example, non_increasing) |
| 25 | + [9, 7, 4, 2, 1] |
| 26 | + >>> bubble_sort(example) |
| 27 | + [1, 2, 4, 7, 9] |
| 28 | + """ |
| 29 | + list_len = len(input) |
| 30 | + for num_sorted in xrange(list_len - 1): |
| 31 | + # subtract num_sorted from inner loop -- end is already sorted |
| 32 | + for i in xrange(0, list_len - num_sorted - 1): |
| 33 | + # test if the element should be swapped with next element |
| 34 | + if not compare(input[i], input[i+1]): |
| 35 | + input[i], input[i+1] = input[i+1], input[i] |
| 36 | + return input |
| 37 | + |
| 38 | +if __name__ == "__main__": |
| 39 | + # a check to make sure that docs are up to date |
| 40 | + import doctest |
| 41 | + doctest.testmod() |
0 commit comments