Skip to content
myAudience.
← Explore the library

Putting a sequence in order

By Code from zero · myAudience

AI-generated original illustration: Putting a sequence in order

myAudience · AI-generated original illustration · Original AI-generated illustration; not documentary evidence; no third-party artwork reproduced.

Sorting puts items into an order defined by a comparison rule. Numeric ascending order, alphabetical order and ordering by a date are different rules. A computer cannot infer that a sequence should look nice; it needs a consistent way to compare two items and determine which should come first.

One simple method is insertion sort. Start with a sorted prefix, take the next item, and insert it into the appropriate position in that prefix. The sorted region grows one item at a time. This explanation describes the algorithm’s state, rather than only showing a finished list and assuming that the process is obvious.

Comparison rules must handle ties and the data type correctly. The text values "10" and "2" can have a different alphabetical order from the numbers 10 and 2. A stable sorting method preserves the original relative order of items considered equal, which can matter when a second field records an earlier ordering.

Worked example: sort [5, 2, 4, 1] numerically. Insert 2 before 5 to get [2, 5]; insert 4 between them to get [2, 4, 5]; insert 1 at the beginning to get [1, 2, 4, 5]. Check: why is comparing numeric strings as ordinary text risky? Character order is not the same rule as numeric magnitude.

The illustrated cards are generated objects, not benchmark data. To evaluate an implementation, test an empty list, one item, duplicates, already sorted items and reverse order. For large inputs, compare measured behavior under stated conditions and analyze the algorithm, rather than declaring it fast because four cards were easy to arrange.

Image: illustration, not a documentary photograph.

Author source references