From a3ac146cb454572522033fd8c489c67cbd0e9c15 Mon Sep 17 00:00:00 2001 From: weiyunfei16 <1872416452@qq.com> Date: Thu, 26 Feb 2026 16:39:26 +0800 Subject: [PATCH] Add bubble sort implementation in Python Implement standard and optimized bubble sort algorithms with example usage. Co-Authored-By: Claude Opus 4.6 --- bubble_sort.py | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 bubble_sort.py diff --git a/bubble_sort.py b/bubble_sort.py new file mode 100644 index 0000000..05a2843 --- /dev/null +++ b/bubble_sort.py @@ -0,0 +1,58 @@ +def bubble_sort(arr): + """ + Sort an array using bubble sort algorithm. + + Args: + arr (list): List of comparable elements to be sorted. + + Returns: + list: Sorted list in ascending order. + """ + n = len(arr) + # Traverse through all array elements + for i in range(n): + # Last i elements are already in place + for j in range(0, n - i - 1): + # Traverse the array from 0 to n-i-1 + # Swap if the element found is greater than the next element + if arr[j] > arr[j + 1]: + arr[j], arr[j + 1] = arr[j + 1], arr[j] + return arr + + +def bubble_sort_optimized(arr): + """ + Optimized bubble sort that stops if no swaps occur in a pass. + + Args: + arr (list): List of comparable elements to be sorted. + + Returns: + list: Sorted list in ascending order. + """ + n = len(arr) + for i in range(n): + swapped = False + # Last i elements are already in place + for j in range(0, n - i - 1): + if arr[j] > arr[j + 1]: + arr[j], arr[j + 1] = arr[j + 1], arr[j] + swapped = True + # If no two elements were swapped in inner loop, then break + if not swapped: + break + return arr + + +if __name__ == "__main__": + # Example usage + example_arr = [64, 34, 25, 12, 22, 11, 90] + print("Original array:", example_arr) + + # Test standard bubble sort + sorted_arr = bubble_sort(example_arr.copy()) + print("Sorted array (standard):", sorted_arr) + + # Test optimized bubble sort + optimized_arr = bubble_sort_optimized(example_arr.copy()) + print("Sorted array (optimized):", optimized_arr) \ No newline at end of file