Pure implementation of bubble sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> bubble_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> bubble_
(collection)
| 2 | |
| 3 | |
| 4 | def bubble_sort(collection): |
| 5 | """Pure implementation of bubble sort algorithm in Python |
| 6 | |
| 7 | :param collection: some mutable ordered collection with heterogeneous |
| 8 | comparable items inside |
| 9 | :return: the same collection ordered by ascending |
| 10 | |
| 11 | Examples: |
| 12 | >>> bubble_sort([0, 5, 3, 2, 2]) |
| 13 | [0, 2, 2, 3, 5] |
| 14 | |
| 15 | >>> bubble_sort([]) |
| 16 | [] |
| 17 | |
| 18 | >>> bubble_sort([-2, -5, -45]) |
| 19 | [-45, -5, -2] |
| 20 | |
| 21 | >>> bubble_sort([-23,0,6,-4,34]) |
| 22 | [-23,-4,0,6,34] |
| 23 | """ |
| 24 | length = len(collection) |
| 25 | for i in range(length-1): |
| 26 | swapped = False |
| 27 | for j in range(length-1-i): |
| 28 | if collection[j] > collection[j+1]: |
| 29 | swapped = True |
| 30 | collection[j], collection[j+1] = collection[j+1], collection[j] |
| 31 | if not swapped: break # Stop iteration if the collection is sorted. |
| 32 | return collection |
| 33 | |
| 34 | |
| 35 | if __name__ == '__main__': |