# Move through the entire array swapping elements if they are out of order.
# Because of the swaps throughout the entire array, it is ensured that one
# pass of these swaps will result in the last index containing the largest
# element.
# So, in the next passes, we exclude the last element from these swaps.
# If there are no swaps that have taken place in this pass, it means the
# entire array is sorted and we can break early.
def bubbleSort(arr):
for j in range(len(arr) - 1, -1, -1):
swapped = False
for i in range(j):
if arr[i + 1] < arr[i]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
swapped = True
if not swapped:
break
arr = [2, -4, -13, 6, 14, 16, -9, -5, 1, 7]
bubbleSort(arr)
print(arr)
To embed this program on your website, copy the following code and paste it into your website's HTML: