Bubble Sort is the simplest sorting algorithm. It works by repeatedly swapping adjacent elements if they are in the wrong order. Large values "bubble up" to the end of the array with each full pass.
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
# Swap elements
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
# Optimization: If no two elements were swapped in inner loop, array is sorted
if not swapped:
break
return arr
swapped flag optimization).