Bubble Sort in Python
A bubble sort, as the name implies, involves using a bubble of 2 elements within which a swap occurs if the elements are not in the correct order. Each iteration of the bubble sort performs n-1 comparisons. By repeating this bubbling for n-1 iterations, we get the input data sorted.
The bubble sort algorithm is simple enough to implement an in-place sort in just 4 lines of Python:
def bubble_sort(input_list):
# TODO Implement a flag to check if there were any swaps in the first iteration;
# if there were none (i.e. it's already sorted), stop right there
for j in range(len(input_list) - 1):
for i in range(len(input_list) - 1 - j):
if input_list[i] > input_list[i + 1]:
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
my_list = [6, 3, 5, 4, 1, 1, 2]
bubble_sort(my_list)
print(my_list)
The bubble sort is inefficient at sorting larger input data. Bubble sort performs better than stooge sort and bogo sort.