Unays Learn · Algorithms

Searching and sorting: your first algorithms

An algorithm is a precise set of steps for solving a problem. Searching and sorting are the classic first algorithms, and they show why the way you solve a problem matters as much as solving it.

Bubble sort

Bubble sort repeatedly swaps neighbours that are in the wrong order, so the largest values "bubble" to the end:

def bubble_sort(items):
    items = items[:]  # work on a copy
    for end in range(len(items) - 1, 0, -1):
        swapped = False
        for i in range(end):
            if items[i] > items[i + 1]:
                items[i], items[i + 1] = items[i + 1], items[i]
                swapped = True
        if not swapped:
            break  # already sorted
    return items

print(bubble_sort([5, 1, 4, 2, 8]))  # [1, 2, 4, 5, 8]

It is easy to understand but slow on big lists: roughly n² comparisons.

Comparing speed with Big O

Programmers describe how work grows with input size using Big O notation:

  • O(n), linear search: twice the data, twice the work.
  • O(log n), binary search: twice the data, just one more step.
  • O(n²), bubble sort: twice the data, four times the work.
  • O(n log n): the best general sorting algorithms, such as merge sort. Python's built-in sorted() uses an algorithm in this class.

In real programs, use the built-in sorted() or list.sort(). Writing your own sort is for learning how they work.

Try it yourself

In Unays Code, add a counter to linear_search and binary_search to count comparisons, then search a sorted list of 100,000 numbers with each. Compare the counts.

This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].