Pure implementation of bubble sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered in ascending order Examples: >>> bubble_sort_iterative([0, 5, 2, 3, 2]) [0, 2, 2, 3, 5]
(collection: list[Any])
| 2 | |
| 3 | |
| 4 | def bubble_sort_iterative(collection: list[Any]) -> list[Any]: |
| 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 in ascending order |
| 10 | |
| 11 | Examples: |
| 12 | >>> bubble_sort_iterative([0, 5, 2, 3, 2]) |
| 13 | [0, 2, 2, 3, 5] |
| 14 | >>> bubble_sort_iterative([]) |
| 15 | [] |
| 16 | >>> bubble_sort_iterative([-2, -45, -5]) |
| 17 | [-45, -5, -2] |
| 18 | >>> bubble_sort_iterative([-23, 0, 6, -4, 34]) |
| 19 | [-23, -4, 0, 6, 34] |
| 20 | >>> bubble_sort_iterative([1, 2, 3, 4]) |
| 21 | [1, 2, 3, 4] |
| 22 | >>> bubble_sort_iterative([3, 3, 3, 3]) |
| 23 | [3, 3, 3, 3] |
| 24 | >>> bubble_sort_iterative([56]) |
| 25 | [56] |
| 26 | >>> bubble_sort_iterative([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2]) |
| 27 | True |
| 28 | >>> bubble_sort_iterative([]) == sorted([]) |
| 29 | True |
| 30 | >>> bubble_sort_iterative([-2, -45, -5]) == sorted([-2, -45, -5]) |
| 31 | True |
| 32 | >>> bubble_sort_iterative([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34]) |
| 33 | True |
| 34 | >>> bubble_sort_iterative(['d', 'a', 'b', 'e']) == sorted(['d', 'a', 'b', 'e']) |
| 35 | True |
| 36 | >>> bubble_sort_iterative(['z', 'a', 'y', 'b', 'x', 'c']) |
| 37 | ['a', 'b', 'c', 'x', 'y', 'z'] |
| 38 | >>> bubble_sort_iterative([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6]) |
| 39 | [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7] |
| 40 | >>> bubble_sort_iterative([1, 3.3, 5, 7.7, 2, 4.4, 6]) |
| 41 | [1, 2, 3.3, 4.4, 5, 6, 7.7] |
| 42 | >>> import random |
| 43 | >>> collection_arg = random.sample(range(-50, 50), 100) |
| 44 | >>> bubble_sort_iterative(collection_arg) == sorted(collection_arg) |
| 45 | True |
| 46 | >>> import string |
| 47 | >>> collection_arg = random.choices(string.ascii_letters + string.digits, k=100) |
| 48 | >>> bubble_sort_iterative(collection_arg) == sorted(collection_arg) |
| 49 | True |
| 50 | """ |
| 51 | length = len(collection) |
| 52 | for i in reversed(range(length)): |
| 53 | swapped = False |
| 54 | for j in range(i): |
| 55 | if collection[j] > collection[j + 1]: |
| 56 | swapped = True |
| 57 | collection[j], collection[j + 1] = collection[j + 1], collection[j] |
| 58 | if not swapped: |
| 59 | break # Stop iteration if the collection is sorted. |
| 60 | return collection |
| 61 |