|
| 1 | +"""Bubble Sort Algorithm. |
| 2 | +
|
| 3 | +This module implements the bubble sort algorithm, a simple sorting technique |
| 4 | +that repeatedly steps through the list, compares adjacent elements and swaps |
| 5 | +them if they are in the wrong order. |
| 6 | +""" |
| 7 | + |
| 8 | + |
| 9 | +def bubble_sort(arr: list[int | float]) -> list[int | float]: |
| 10 | + """ |
| 11 | + Sort an array using the bubble sort algorithm. |
| 12 | +
|
| 13 | + Bubble sort works by repeatedly swapping adjacent elements if they are |
| 14 | + in the wrong order. This process continues until no more swaps are needed. |
| 15 | +
|
| 16 | + Args: |
| 17 | + arr: List of numbers to be sorted |
| 18 | +
|
| 19 | + Returns: |
| 20 | + The sorted list in ascending order |
| 21 | +
|
| 22 | + Examples: |
| 23 | + >>> bubble_sort([64, 34, 25, 12, 22, 11, 90]) |
| 24 | + [11, 12, 22, 25, 34, 64, 90] |
| 25 | + >>> bubble_sort([5, 2, 8, 1, 9]) |
| 26 | + [1, 2, 5, 8, 9] |
| 27 | + >>> bubble_sort([1]) |
| 28 | + [1] |
| 29 | + >>> bubble_sort([]) |
| 30 | + [] |
| 31 | + >>> bubble_sort([3, 3, 3, 3]) |
| 32 | + [3, 3, 3, 3] |
| 33 | + >>> bubble_sort([5, 4, 3, 2, 1]) |
| 34 | + [1, 2, 3, 4, 5] |
| 35 | + >>> bubble_sort([1.5, 2.3, 0.8, 1.1]) |
| 36 | + [0.8, 1.1, 1.5, 2.3] |
| 37 | + """ |
| 38 | + # Create a copy to avoid modifying the original list |
| 39 | + arr_copy = arr.copy() |
| 40 | + n = len(arr_copy) |
| 41 | + |
| 42 | + # Traverse through all array elements |
| 43 | + for i in range(n): |
| 44 | + # Flag to optimize by detecting if array is already sorted |
| 45 | + swapped = False |
| 46 | + |
| 47 | + # Last i elements are already in place |
| 48 | + for j in range(0, n - i - 1): |
| 49 | + # Swap if the element found is greater than the next element |
| 50 | + if arr_copy[j] > arr_copy[j + 1]: |
| 51 | + arr_copy[j], arr_copy[j + 1] = arr_copy[j + 1], arr_copy[j] |
| 52 | + swapped = True |
| 53 | + |
| 54 | + # If no swapping occurred, array is sorted |
| 55 | + if not swapped: |
| 56 | + break |
| 57 | + |
| 58 | + return arr_copy |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + import doctest |
| 63 | + |
| 64 | + doctest.testmod() |
0 commit comments