liveBook · Manning

Quicksort

As explained in Software Design for Python Programmers

Quicksort is a comparison-sorting algorithm that selects a pivot, partitions values around it, and recursively sorts the resulting sublists.

Quicksort sorts by choosing a pivot, partitioning values around it, and recursively sorting the sublists on either side. The pivot reaches its final position during partitioning. section 15.6

Apply the algorithm in this sequence:

  • Choose a pivot, move it aside, and scan inward with indexes i and j. section 15.6.2
  • Swap out-of-place values while i remains left of j, then restore the pivot between the two sublists. section 15.6.2
  • Stop for sublists of size zero or one; swap a reversed pair of size two; otherwise recurse on both sides. section 15.6

Python implementation

A Quicksort class separates swapping, partitioning, recursive sorting, and verification. Its demonstration sorts twenty random values in place and reports success after checking adjacent pairs. section 15.6.3

Figure 15.12 Choosing 52 (circled) to be the pivot value and then partitioning the list into two sublists. Variables i and j are list indexes. After partitioning, all values to the left of 52 are less than or equal to it, and all values to the right of 52 are greater. The two boxed sublists on either side of the pivot are now ready to be recursively quicksorted.
A screenshot of a math test

AI-generated content may be incorrect.

Follow the pivot 52 through index scans and swaps to see how one list becomes two recursively sortable sublists. section 15.6.2

How Software Design for Python Programmers covers it

How deep it goes
Descends through pivot partitioning, index movement, swaps, base cases, recursive calls, and a complete Python implementation.
Examples
Demonstrates pivot 7 in a sorting trace, pivot 52 during partitioning, and twenty randomly generated Python values.
What it assumes
Assumes lists, indexes, comparisons, swapping, and recursion; teaches the partitioning process and its stopping cases.
What you can do after
Build it from scratch as an in-place Python sorter with recursive partitioning and sortedness verification.
How it connects
Connects sorting with recursion, partitioning, pivots, sublists, indexes, and base cases.

Also explained in

Compare how 3 books explain quicksort →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.