liveBook · Manning

Sorting algorithm

As explained in The Quick Python Book, Fourth Edition

A sorting algorithm is a procedure that rearranges elements of a collection into an order determined by an ordering criterion.

Sorting arranges elements by their values or by a specified key. Python’s list.sort() changes the list in place; sorted() returns a sorted copy, preserving the original order. section 5.4

Choose the sorting approach to fit the data and task:

  • Use reverse=True for reverse order, or key= to compare elements by a chosen value, such as lowercase text. section 5.4 section 21.4.2
  • Default sorting requires comparable item types; mixing numbers and strings raises a TypeError. Lists of lists sort by their elements in order. section 5.4
  • For large files, weigh memory against convenience: sorted() creates a copy, while an external utility such as UNIX sort can preprocess data larger than memory. section 21.4.2
  • Keep key functions simple: they are called repeatedly during sorting, and complex work can slow large sorts. section 21.4.2

Sorting for a median

A temperature list can be sorted in place, then indexed to select a middle value. Alternatively, sort a copy and average the two middle values when the list has an even number of entries. section 5.9.3

x = [2, 4, 1, 3]
y = x[:]                #1
y.sort()                #2
y
 
[1, 2, 3, 4]
 
x
 
[2, 4, 1, 3]
#1 A full list slice makes a copy of the list.
#2 Sorts method on copy, not original

See how sorting a full-slice copy orders the copy while leaving the original list unchanged. section 5.4

! sort datafile > datafile.srt
! cat datafile.srt
 
AAAAAA
CCCCCC
QQQQQQ
ZZZZZZ

See an external sort utility ordering rows from a data file. section 21.4.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains in-place and copied sorting, comparison rules, keys, memory trade-offs, and file-size alternatives; stops short of algorithm internals.
Examples
Uses numbers, strings, nested lists, temperature records, and text-file rows as sorting examples.
What you can do after
Apply it via Python’s list.sort(), sorted(), or UNIX sort to order collections and file rows.
How it connects
Connects list methods and key functions with median calculation and data-file processing.

Also explained in

Compare how 18 books explain sorting algorithm →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.