🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Sorting and Graph Algorithms Implemented from Scratch

Python AlgorithmsAlgorithm Implementation🟢 Free Lesson

Sorting and Graph Algorithms Implemented from Scratch

Interview culture teaches you to implement merge sort from memory; production culture teaches you when not to. Both lessons matter. Writing these algorithms once, carefully, gives you a mental model of their trade-offs that no amount of calling sorted() will — and that model is what tells you, six months later, whether the slow report is a sorting problem, a graph problem, or simply a Python loop that should have been a dictionary lookup. The implementations here are deliberately plain: no clever tricks, just the structure that makes each algorithm work and the invariant that makes it correct.


Sorting: the two shapes worth knowing

Comparison sorting has two canonical divide-and-conquer shapes. Merge sort splits the list in half, sorts each half recursively, and merges — guaranteeing its worst case but needing auxiliary memory. Quicksort partitions around a pivot and recurses on the sides — usually faster in practice, but only as good as the pivot choice.

python
def merge_sort(items):
    if len(items) <= 1:
        return list(items)

    mid = len(items) // 2
    left = merge_sort(items[:mid])
    right = merge_sort(items[mid:])

    result, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i]); i += 1
        else:
            result.append(right[j]); j += 1
    result.extend(left[i:])
    result.extend(right[j:])
    return result


def quick_sort(items):
    if len(items) <= 1:
        return list(items)

    pivot = items[len(items) // 2]
    smaller = [x for x in items if x < pivot]
    equal = [x for x in items if x == pivot]
    larger = [x for x in items if x > pivot]
    return quick_sort(smaller) + equal + quick_sort(larger)

The <= in the merge loop is what keeps the sort stable: equal elements keep their original relative order. Stability is not academic — it is why a second sort by another key can refine a first sort without undoing it, and it is what sorted guarantees when you sort records by multiple fields in reverse order of priority.

Complexity in the real world

Asymptotics describe growth, not speed. A constant-factor difference — Python-level element moves versus a C memmove — can swamp a better big-O class at the sizes you actually handle.

AlgorithmBestAverageWorstExtra memoryStable
Insertion sortnn²n²O(1)Yes
Merge sortn log nn log nn log nO(n)Yes
Quicksort (good pivot)n log nn log nn²O(log n)No
Timsort (sorted)nn log nn log nO(n)Yes
Counting sortn + kn + kn + kO(k)Yes
Heap sortn log nn log nn log nO(1)No

The practical reading of this table: for general Python lists, call sorted — Timsort exploits existing runs in real data and is implemented in C. Implement the algorithms when you need the reasoning: counting sort when keys are small integers, insertion sort for tiny arrays inside a hybrid, merge sort when stability and worst-case guarantees matter more than constants.

Search: binary search and its invariants

The same discipline applies to searching. Binary search is four lines of arithmetic and one invariant: the answer, if it exists, always lies inside the current bounds. Most bugs come from updating the bounds so the invariant no longer holds — using mid - 1 when the target could still be at mid, or looping while left < right when the range must be allowed to collapse to a single candidate.

python
def binary_search(items, target):
    left, right = 0, len(items) - 1
    while left <= right:                 # invariant: answer is within [left, right]
        mid = (left + right) // 2
        if items[mid] == target:
            return mid
        if items[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

def lower_bound(items, target):
    """First index whose value is >= target (may equal len(items))."""
    left, right = 0, len(items)
    while left < right:
        mid = (left + right) // 2
        if items[mid] < target:
            left = mid + 1
        else:
            right = mid
    return left

The second function is the one worth memorising. Insertion points, rank queries, and "find the first row satisfying X" all reduce to lower_bound, and the half-open range [left, right) avoids the fencepost reasoning that trips up the closed-range version. Both functions assume sorted input — which is exactly the kind of precondition worth asserting once at the call site rather than trusting silently.

Representing graphs: adjacency lists and matrices

A graph in code is a choice of representation, and that choice fixes your complexity bounds before you write a single traversal. Adjacency lists use memory proportional to the edges and iterate neighbours quickly — the right default for sparse graphs, which is almost always what you have. An adjacency matrix gives constant-time edge lookups at the cost of vertices-squared memory.

python
from collections import defaultdict, deque

class Graph:
    def __init__(self, directed=False):
        self.adjacency = defaultdict(set)
        self.directed = directed

    def add_edge(self, u, v):
        self.adjacency[u].add(v)
        if not self.directed:
            self.adjacency[v].add(u)

    def bfs(self, start):
        visited = {start}
        queue = deque([start])
        order = []
        while queue:
            node = queue.popleft()
            order.append(node)
            for neighbour in self.adjacency[node]:
                if neighbour not in visited:
                    visited.add(neighbour)
                    queue.append(neighbour)
        return order

    def dfs(self, start):
        visited, order = set(), []
        stack = [start]
        while stack:
            node = stack.pop()
            if node in visited:
                continue
            visited.add(node)
            order.append(node)
            stack.extend(self.adjacency[node] - visited)
        return order

Note the deque in the breadth-first search: a list with pop(0) would make the traversal quadratic for no reason, which is the single most common performance mistake in hand-written graph code. The depth-first version uses an explicit stack, avoiding recursion limits on graphs with long paths.

Dijkstra: priorities, not plain queues

The difference between breadth-first search and Dijkstra is the queue. BFS assumes every edge costs the same, so a FIFO queue suffices; weighted graphs need a priority queue that always expands the cheapest known path next, plus a relaxation step that updates neighbour distances when a better route appears.

python
import heapq

def dijkstra(graph, source):
    # graph.adjacency[node] is an iterable of (neighbour, weight) pairs
    distances = {node: float("inf") for node in graph.adjacency}
    distances[source] = 0
    previous = {node: None for node in graph.adjacency}
    frontier = [(0, source)]
    settled = set()

    while frontier:
        current_dist, node = heapq.heappop(frontier)
        if node in settled:
            continue                      # stale entry — a better path already won
        settled.add(node)

        for neighbour, weight in graph.adjacency[node]:
            candidate = current_dist + weight
            if candidate < distances[neighbour]:
                distances[neighbour] = candidate
                previous[neighbour] = node
                heapq.heappush(frontier, (candidate, neighbour))

    return distances, previous

def reconstruct_path(previous, target):
    path = []
    while target is not None:
        path.append(target)
        target = previous[target]
    return path[::-1]

The if node in settled: continue line is the part interviewees forget. Python's heapq has no decrease-key operation, so the standard workaround pushes duplicate entries and discards the stale ones when they surface — without that check the algorithm still produces correct distances but wastes work proportional to the number of relaxations.

Choosing an algorithm for the data you actually have

The right algorithm is the one that matches your data's shape, not the one in the paper. Shortest paths on a sparse road network want Dijkstra with a binary heap; on a dense matrix of pairwise distances, repeated Dijkstra is worse than running Floyd–Warshall once. Connected components want BFS or union–find, not a stack of recursive DFS calls that overflows at depth a thousand. Topological order wants an explicit queue with an in-degree count — Kahn's algorithm — because it surfaces cycles instead of crashing into a recursion limit.

And when the data is small — a few thousand items — the algorithm often does not matter at all, and the honest optimisation is to remove the work rather than speed it up: index by key instead of scanning, precompute instead of re-deriving, and only then reach for a cleverer algorithm with a proof attached.

The final discipline is to write down the precondition each function assumes. Merge sort needs a list it may copy; binary search needs ascending order; Dijkstra needs non-negative weights, and a single negative edge silently produces wrong distances. Assertions at the top of the function cost nothing and convert a mysterious wrong answer into a clear failure at the call site — the same principle that makes an explicit invariant in a loop body worth the extra line.

Common Mistakes

Using list.pop(0) in a hand-written BFS

Fix: Use collections.deque so each pop is constant time

Implementing quicksort with the first element as pivot on sorted input

Fix: Choose a middle or random pivot, or switch to Timsort via sorted()

Forgetting to skip stale heap entries in Dijkstra

Fix: Track settled nodes and continue past entries already expanded

Reimplementing comparison sorts for production code

Fix: Call sorted() — it is stable, C-implemented, and tuned for real data

Using recursion for DFS on deep graphs

Fix: Use an explicit stack so long paths do not hit the recursion limit

Best Practices

  • State the stability guarantee you rely on before sorting records by multiple keys
  • Default to adjacency lists; reach for a matrix only when edge lookups dominate
  • Choose representations that make the hot operation cheap, not the construction
  • Write the loop invariant next to the merge or relaxation step — it documents correctness
  • Profile against realistic sizes before replacing a library call with a hand-rolled algorithm

Key Takeaways

  • Merge sort is stable with a guaranteed n log n; quicksort is usually faster until the pivot betrays you
  • Timsort behind sorted() beats hand-written Python sorts at realistic sizes
  • Adjacency lists suit sparse graphs and make BFS and DFS linear in the edges
  • Dijkstra differs from BFS only in the queue: a priority queue plus a relaxation step
  • Stale heap entries must be skipped explicitly because heapq lacks decrease-key
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement