25 lines
666 B
Python
25 lines
666 B
Python
def bubble_sort(arr):
|
|
n = len(arr)
|
|
for i in range(n - 1):
|
|
swapped = False # To detect whether the move has been made at this stage or not
|
|
|
|
# Comparing adjacent elements
|
|
for j in range(n - i - 1): # -i because the largest elements are fixed at the end
|
|
if arr[j] > arr[j + 1]:
|
|
# Swap
|
|
arr[j], arr[j + 1] = arr[j + 1], arr[j]
|
|
swapped = True
|
|
|
|
# If no moves were made, the array was already sorted → Done!
|
|
if not swapped:
|
|
break
|
|
|
|
|
|
# Example:
|
|
|
|
nums = [5, 2, 4, 6, 1, 3]
|
|
print("Before sorting:", nums)
|
|
|
|
bubble_sort(nums)
|
|
print("After sorting:", nums)
|