Bubble Sort
Bubble sort compares adjacent elements and swaps out-of-order pairs. It is useful for learning local comparisons, though it is usually unsuitable for large production inputs.
Understand the idea
Each pass moves a large remaining value toward the right. An unchanged pass permits an early exit. Worst-case time is quadratic, while this implementation makes a copy so callers keep their input unchanged. For production sorting, Python's stable built-in sorted is usually more efficient and better tested.
Where to try it
Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.
A worked example
def bubble_sort(values):
result = list(values)
for end in range(len(result) - 1, 0, -1):
changed = False
for index in range(end):
if result[index] > result[index + 1]:
result[index], result[index + 1] = result[index + 1], result[index]
changed = True
if not changed:
break
return result
print(bubble_sort([8, 3, 5, 3]))
Read the result
The sorted copy is [3, 3, 5, 8], preserving both occurrences of 3.
Try one change
Test an already sorted input and count how the early-exit flag changes the work.