Sorting
Start with arranging books and prices, then understand the steps computers use to put things in order.
sorting, ordering, comparison, stability, complexity, algorithmsWhat sorting means
Imagine five books with number stickers: 5, 2, 4, 1, and 3. You want them on a shelf from the smallest number to the largest. You move the books until their stickers read 1, 2, 3, 4, 5. That is sorting: putting things in a chosen order. No book is added or thrown away.
An algorithm is a clear set of steps for doing a job, like instructions for arranging those books. A computer needs those steps; it cannot simply be told to "make the shelf look right" without a rule for what right means.
Sorting rearranges a collection according to an ordering rule. Ascending numeric
order changes [5, 2, 4, 1] into [1, 2, 4, 5]. The result must be ordered
and contain exactly the original elements, including repeated values.
The ordering rule need not be numeric. We can order names alphabetically or records by a timestamp. A record's key is the value used to compare it. For now, use ordinary numbers that can be compared. Later, special values such as NaN ("not a number") require a deliberately chosen ordering rule.
Why ordering helps
Suppose a shopping list shows prices 50, 20, 40, 10. Put them in increasing order and it becomes easier to compare cheap and expensive choices. Sorting does not change the prices; it makes their order useful.
Order exposes structure. The smallest and largest values become easy to locate; equal keys become neighbours; a sorted collection can support efficient search. Sorting has a cost, however. Sorting a large collection just to find its minimum is unnecessary: a single scan can find the minimum without ordering everything.
Where sorting is used
- A library can arrange titles alphabetically so readers know where to look.
- A shop can show items from lowest price to highest price.
- A calendar can put events in date order.
- A list of marks can be ordered to make the middle value easier to find.
These are uses of sorting, not proof that these systems use Bubble Sort. Real software usually uses well-tested library sorting methods. We study the three small algorithms here because their decisions are easy to explain.
Comparing and preserving information
A comparison asks which of two things should come first. A swap exchanges their positions. A pass is one trip through the part of a list an algorithm is examining. The prefix is the part on the left; the suffix is the part on the right. You do not need to memorise these words before trying an example.
A comparison-based sort asks questions such as "is the left value greater than the right value?" Its strategy determines which comparisons happen and when elements move. For equal-key records, stability means preserving their original relative order.
Suppose Ada:80 appears before Lin:80. A stable sort by mark keeps Ada before
Lin. Stability does not mean the whole input stays unchanged; only the relative
order of equal-key items is protected.
An in-place algorithm uses only constant auxiliary storage beyond the input. A simple picture is rearranging books on the same shelf while keeping only a small amount aside, rather than making a second shelf for all the books. A function can sort in place even if it returns the same list for convenience. Returning a list is not itself evidence that a new list was allocated.
Three basic strategies
Think of three ways to organise the shelf:
- Bubble: compare two neighbouring books and exchange them if needed.
- Selection: find the smallest remaining book and put it in the next place.
- Insertion: keep the left-hand books in order and slide the next book into them.
The table below is a deeper comparison. Time complexity describes how the
amount of work grows when there are more items, not the exact seconds on a clock.
n means "how many items". O(n) means work grows roughly with that number;
O(n²) means work can grow roughly with its square. O(1) extra space means the
extra storage does not grow with the number of items.
| Algorithm | Main idea | Best time | Average / worst time | Extra space | Stable here? |
|---|---|---|---|---|---|
| Bubble Sort | Swap out-of-order neighbours | O(n), with early stopping | O(n²) | O(1) | Yes |
| Selection Sort | Find the next minimum | O(n²) | O(n²) | O(1) | No |
| Insertion Sort | Insert into a sorted prefix | O(n) | O(n²) | O(1) | Yes |
Here n is the number of elements. Average-case quadratic time refers to the
usual random-order model with distinct keys. The table describes the specific
implementations in this section, not every possible variant.
A worked example
For [5, 2, 4, 1], Bubble Sort's first left-to-right pass performs:
- Compare 5 and 2; swap:
[2, 5, 4, 1]. - Compare 5 and 4; swap:
[2, 4, 5, 1]. - Compare 5 and 1; swap:
[2, 4, 1, 5].
The largest value is now in its final position, but the remaining prefix is not yet sorted. An intermediate state is not a finished result.
Python illustration
For ordinary application code, prefer Python's built-in sorting tools rather than reimplementing a teaching algorithm.
values = [5, 2, 4, 1]
ordered = sorted(values)
print(ordered)
print(values)
Prepared output — not live execution:
[1, 2, 4, 5]
[5, 2, 4, 1]
sorted creates a new list. In contrast, values.sort() modifies the list in
place and returns None. Python's built-in sorts are stable; they are not the
three quadratic teaching algorithms listed above.
Choosing an algorithm
Learning these strategies builds intuition about invariants, comparisons, and data movement. They are not a recommendation to use quadratic algorithms for large arbitrary inputs. Consider input size, existing order, stability, extra storage, and the cost of moving records before choosing a strategy.
Start with Bubble Sort, then compare its strategy with Selection Sort and Insertion Sort.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
