From 69a7fd5265dfb52998b25fb0e09de740397dd931 Mon Sep 17 00:00:00 2001 From: Aviral Jain <74827110+Aviral1-jain@users.noreply.github.com> Date: Thu, 2 Oct 2025 13:28:15 +0530 Subject: [PATCH] bubble_sort.py --- Python/sorting/bubble_sort.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/sorting/bubble_sort.py diff --git a/Python/sorting/bubble_sort.py b/Python/sorting/bubble_sort.py new file mode 100644 index 0000000..67a9f4e --- /dev/null +++ b/Python/sorting/bubble_sort.py @@ -0,0 +1,32 @@ +def bubble_sort(arr): + + # Outer loop to iterate through the list n times + for n in range(len(arr) - 1, 0, -1): + + # Initialize swapped to track if any swaps occur + swapped = False + + # Inner loop to compare adjacent elements + for i in range(n): + if arr[i] > arr[i + 1]: + + # Swap elements if they are in the wrong order + arr[i], arr[i + 1] = arr[i + 1], arr[i] + + # Mark that a swap has occurred + swapped = True + + # If no swaps occurred, the list is already sorted + if not swapped: + break + + +# Sample list to be sorted +arr = [6,6,2] +print("Unsorted list is:") +print(arr) + +bubble_sort(arr) + +print("Sorted list is:") +print(arr)