+91 81900 98289

Bubble Sort

This Bubble Sort lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

Bubble sort walks the list and swaps neighbours that are out of order. Large values drift to the end.

It is easy to see and slow on long lists. Use it to learn swaps, not to sort production data.

Example 1: Start here

The copy keeps the caller list unchanged.

def bubble(items): # define the function; it runs when you call it items = items[:] # a separate copy for i in range(len(items)): # repeat once per number; range stops before the last for j in range(len(items) - 1 - i): # repeat once per number; range stops before the last if items[j] > items[j + 1]: # run the indented lines only when this is true items[j], items[j + 1] = items[j + 1], items[j] # swap the two values return items # send this value back to the caller print(bubble([4, 1, 3]))

Example 2: Walk the values

Bubble Sort starts by visiting one value at a time. Read the printed lines from top to bottom.

values = [13, 3, 11, 7] # a list; the values stay in this order for value in values: # repeat the indented lines once per value print(value)

Example 3: Keep the largest

Many data-structure lessons reduce a list to one answer. This one remembers the largest number seen so far.

values = [13, 3, 11, 7] # a list; the values stay in this order best = values[0] # the first value for value in values: # repeat the indented lines once per value if value > best: # run the indented lines only when this is true best = value # another name for the same value print(best)

Example 4: Search for a target

A search asks one yes-or-no question: is the target in the collection? Bubble Sort builds on that question.

values = [3, 13, 11] # a list; the values stay in this order target = 13 # a whole number print(target in values) # in is True when the value is found
The copy keeps the caller list unchanged.
Call Now 81900 98289