Alex Gerdes Created 2026-10-14 Updated 2026-11-05
Alex Gerdes is a computer scientist and a coeditor, with Peter Ljunglöf and Jonas Almström Duregård, of Data Structures and Algorithms edited by Peter Ljunglöf and others. Its treatment connects sorting algorithms with asymptotic analysis and implementation choices. For example, choosing a sorting algorithm involves comparing its growth in work as well as properties such as stability and storage requirements.[ref]
Homepage: www.chalmers.se/en/persons/alexg/
Binary heap Created 2026-10-13 Updated 2026-10-24
A binary heap represents a priority queue as a complete binary tree obeying a heap order. We use the minimum convention: the priority of every parent in a rooted tree is no greater than the priorities of its children in a rooted tree. Equal priorities are allowed. Each stored entry may be a record carrying a priority key; the numerical example below displays only keys. Reversing the inequalities gives the maximum convention.
The complete binary tree can be stored directly in a zero-indexed array : read its levels from top to bottom, left to right. The root of a tree is at index . The possible children in a rooted tree of index are at and , and an index denotes a present entry only when it is less than . For , its parent in a rooted tree is at , using the floor function. Thus the links of the complete binary tree are determined by arithmetic rather than separately stored pointers.
ConsiderThe children in a rooted tree of index have keys ; those of index have keys ; those of index have keys . The six comparisons , , , , , establish the heap order. At index , the parent in a rooted tree is index , carrying key .
The array is visibly not a sorted array: precedes , and precedes . Nor is the last entry a maximum: it is , whereas the maximum is at index . The heap order compares ancestors and descendants, without imposing an order between separate branches. Nevertheless, following the graph path from the root of a tree to any entry gives a chain of nondecreasing priorities. This short argument proves that
peek can return , a minimum, without inspecting the other entries.Insertion appends an entry to the array, preserving the shape of the complete binary tree, then uses sift up to repair the heap order. Insert key into the displayed binary heap. It is appended at index , and exchanges with indices , , then :The moving key follows ; the keys each move down one level. Only this chain needs repair.
Now apply
extract-min. Save key , move the last key to the root of a tree, and shorten the array to length . Use sift down, always choosing the smaller of the present children in a rooted tree:First exchanges with key at index , since ; then with key at index , since . At index , the possible children in a rooted tree would be indices , both outside the shortened array, so the process stops. The returned key is , and the remaining binary heap is exactly the original one.For a nonempty binary heap with entries, the deepest level is , using the floor function and logarithm. Each exchange moves one level and uses only a bounded number of comparisons. The resulting time complexity bounds, expressed in Big O notation, are:
| Operation | Time complexity | Reason |
|---|---|---|
peek | Read the root of a tree. | |
| Insert | for | Append, then sift up through at most the levels of the complete binary tree. |
extract-min | for | Move the last entry, then sift down through at most those levels. |
| Build from an arbitrary array | Apply sift down from the last index with children in a rooted tree back to index . |
These bounds assume constant-cost indexed access, key comparisons and exchanges, and available array capacity for insertion. Allocating and copying a larger array is a separate cost. Empty and one-entry cases take constant work.
To build a binary heap, begin at index and work backwards. Entries without children in a rooted tree already obey the heap order. Each sift down, also called heapify down, starts with every present smaller rooted tree below it already repaired. Most entries are close to the bottom and can move very little; successively longer repair distances occur for geometrically fewer entries. Summing these distances gives work, rather than charging to every entry. MIT's notes give this bottom-up construction and contrast it with repeated insertion.[ref]
https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/40d4851e550507ca14dc778b9b2266cc_MIT6_006S20_lec8.pdf. MIT 6.006, lecture 8: implicit indices, heap repair and linear build, pp. 3–6
The Dijkstra algorithm additionally needs to decrease the priority of an existing vertex when its tentative distance improves. Given its current index, lowering the key followed by sift up takes time for . An indexed binary heap maintains a separate map from item identity to its current index and updates that map after every exchange. For vertices numbered in a fixed range, the map can be another array, giving constant-time index lookup. An ordinary unindexed binary heap supplies no such guarantee: locating an arbitrary item can require scanning entries. Item identity and priority must remain distinct, especially when several vertices have equal tentative distances.
The attractive compromise is local organization with global usefulness. A binary heap maintains only the heap order, yet every
extract-min gives the next smallest key. Repeated extraction of the original example gives , so a priority queue also supplies a sorting algorithm without storing a sorted array between extractions. Bitonic sequence 2026-10-25
A sequence formed by an ascending part followed by a descending part, or the reverse arrangement, with either part possibly empty. In sorting algorithms, the monotonicity convention normally allows equal keys. Joining one ascending sequence to the reversal of another ascending sequence produces a bitonic sequence.
Differential test 2026-11-05
A differential test runs implementations intended to realize the same contract on matched inputs and compares their observable results. Disagreement reveals an inconsistency without requiring a precomputed answer. Hypothesis explicitly supports comparisons using either a trusted reference or several implementations none of which is fully trusted.[ref]
Integrations Reference in the Hypothesis documentation. equivalent(), reference-oracle and differential-testing examples
For example, compare a new sorting algorithm with a simple reference on lists containing duplicates, negative values and empty input. Compare results under the specified ordering contract; unspecified differences are not failures. Agreement alone cannot exclude a shared software bug. Floating-point arithmetic may require a justified numerical tolerance, and comparison of failures as well as successful outputs requires an explicit error contract.
External merge sort 2026-10-31
A sorting algorithm that sorts memory-sized runs and merges them using storage-backed passes. It can also eliminate repeated database tuples.
Haskell Ord class Created 2026-10-24 Updated 2026-10-31
The Haskell class providing ordering operations, including
compare. A comparison-based sorting algorithm requires the associated constraint to inspect the order of arbitrary keys. Its correctness additionally assumes that the supplied operations obey the intended ordering laws. Information hiding Created 2026-10-13 Updated 2026-10-24
Information hiding makes an implementation decision the responsibility of one software module, whose API lets other code work without knowing that decision. For a FIFO queue, clients need the removal order and failure behavior; they need not know the current front index in an array. This explains why encapsulation is useful beyond object-oriented programming: procedures with hidden storage can provide the same boundary.[ref]
On the Criteria To Be Used in Decomposing Systems into Modules by D. L. Parnas. Parnas, pp. 1054 and 1056, What Is Modularization? and The Criteria: responsibility assignments and hidden design decisions
In On the Criteria To Be Used in Decomposing Systems into Modules by D. L. Parnas (December 1972, pp. 1054–1056), the example applies a sorting algorithm to word rotations of input lines. One decomposition shares storage layouts among processing stages. The alternative exposes line-storage operations such as
CHAR and SETCHAR, hiding whether characters are packed four to a machine word. Changing that packing then belongs to line storage rather than every client. The paper presents a design argument using a deliberately small example, not a universal measured speedup or a claim that classes are required. It also notes that an unnecessarily specified rotation order restricts future implementations (p. 1056, Improvement in Circular Shift Module). Interval scheduling 2026-10-18
Given a finite set of jobs with fixed half-open intervals , where , choose a subset of maximum cardinality. Each job occupies one shared resource throughout its interval. A feasible solution has pairwise disjoint intervals: for distinct selected jobs , either or . Thus a finish and the next start may coincide. Every job has value one; occupied time is not the objective function.[ref]
Lecture 1: Introduction. 6.046J Design and Analysis of Algorithms, Spring 2015; Printed p. 2, Interval Scheduling: fixed requests, one resource, compatibility with endpoint equality, maximum size
Consider these six original jobs, with arbitrary time units:Job can be followed immediately by and . Job conflicts with all three. Starting the resource earlier is therefore not automatically beneficial: one long commitment can displace several shorter requests.
The earliest-finish greedy algorithm uses a sorting algorithm to put jobs in nondecreasing finish time. Scan that order, accepting the first job and then each job whose start is at least the last accepted finish. Break finish-time ties arbitrarily; an empty input returns the empty set. For these jobs, the order and decisions areAfter , job starts before the current finish five and is rejected. Accept ; then reject because six is before seven. Finally accept . The result is , with cardinality four. Leaving idle makes room for more jobs.
By contrast, the earliest-start rule scans . It accepts , skips , accepts , and skips . Its feasible solution contains only two jobs. Here and meet at time six and are compatible; and overlap on .
Earliest finish accepts four jobs; earliest start accepts two
. The same six original intervals appear in both panels. Colored jobs are accepted and gray jobs rejected. A filled start and hollow finish depict a half-open interval; jobs meeting at an endpoint are compatible. Details.There is also an elementary optimality certificate for this example. The four subsets , , and form a partition of a set of the jobs. A feasible solution takes at most one job from each group: overlap, as do , and each other group is a singleton. Hence four is an upper bound, attained by . Checking all subsets gives a unique optimum of size four: .
The earliest-finish theorem states that this greedy algorithm maximizes job count for every finite instance of interval scheduling. For the exchange argument, let be the first job in an optimal feasible solution and an earliest-finishing job. Every later selected job satisfiesReplace by ; compatibility and cardinality survive. The remainder must be optimal among jobs starting at or after , or improving it would improve the whole selection. Mathematical induction on the smaller remaining instance, starting with the empty set, completes the outline.[ref]
Greedy Algorithms. Algorithms by Jeff Erickson; §4.2 Scheduling Classes, Lemma 4.3 and Theorem 4.4, printed pp. 163–164; endpoint equality is allowed by our half-open convention
Why is the algorithm fast? Once sorted, each job is examined once, using only the last accepted finish to decide compatibility. The scan takes time; comparison sorting algorithms give total time complexity for , in Big O notation, assuming constant-cost endpoint comparisons. Already sorted input needs only the scan.[ref]
Lecture 1: Introduction. 6.046J Design and Analysis of Algorithms, Spring 2015; Printed pp. 2–4, earliest-finish rule, compatibility and first-job exchange; scan cost follows by counting one comparison per subsequent request
Kruskal component merging 2026-10-18
A disjoint-set data structure stores the current partition of a set of vertices into connected components of a graph. The operation returns a representative of the block containing . Two vertices are in the same block exactly when their representatives agree. For each candidate edge , compare and . Equal representatives mean reject; different representatives mean accept and perform , merging the two blocks. The representatives are bookkeeping choices, not preferred vertices of the minimum spanning tree.
Connected components of a graph merge only when an edge is accepted
. The same example as a disjoint-set data structure ledger. Each coloured band is one block of the current partition of a set. The rejection of leaves both the partition of a set and the running cost unchanged. Bands show membership, not internal representative pointers. Details.Every acceptance reduces the connected component of a graph count by one and increases the accepted edge count by one, preserving . Thus the ledger reaches exactly when . Only ten representative queries and four merges are needed for the five examined edges, counting two queries per examination and using the already found representatives for each merge. Neither breadth-first search nor reconstruction of a graph path is needed for these connectivity queries.
For and , comparison sorting algorithm takes time for , using Big O notation. One simple disjoint-set data structure implementation stores each block as a rooted tree and attaches the smaller block's root below the larger block's root. Whenever a vertex's depth increases, its block size at least doubles, so its depth is at most . Consequently each representative query or merge takes time. Initialization plus the scan costs ; including sorting algorithm gives , hence for a connected input with . These are operation bounds, not measured timings.[ref]
WeightedQuickUnionUF.java. Robert Sedgewick and Kevin Wayne, Algorithms, 4th edition, companion WeightedQuickUnionUF.java: class documentation and union method; union by size without path compression, linear initialization and logarithmic operations
For heapsort, use the usual array representation of a max-heap, indexed from zero, with children . Build the max-heap from the last internal node towards the root, using heapify down. The three build stages are
start [2,7,3,2,8,1]
sift at index 2 [2,7,3,2,8,1]
sift at index 1 [2,8,3,2,7,1]
sift at index 0 [8,7,3,2,2,1]At index zero, the value
2 moves below 8 and then below 7. Next exchange the root with the last active element, shorten the active heap, and restore heap order. A vertical separator below distinguishes the active prefix from its sorted final suffix.| Removed maximum | After root exchange | After restoring heap order |
|---|---|---|
1,7,3,2,2 | 8 | 7,2,3,1,2 | 8 | |
2,2,3,1 | 7,8 | 3,2,2,1 | 7,8 | |
1,2,2 | 3,7,8 | 2,1,2 | 3,7,8 | |
2,1 | 2,3,7,8 | 2,1 | 2,3,7,8 | |
1 | 2,2,3,7,8 | 1 | 2,2,3,7,8 |
The trace chooses the left child when equal children tie; other tie conventions can give different intermediate heaps with the same sorted output.
For quicksort, use the head as pivot and partition the remaining elements into those strictly less than it and those greater than or equal to it, retaining their order within each partition. This specifies how the duplicate
2 is handled:pivot 2: [1] | 2 | [7,3,2,8]
pivot 7: [3,2] | 7 | [8]
pivot 3: [2] | 3 | []Empty and singleton lists are already sorted. Returning from the recursive calls gives
Q [3,2] = [2] ++ [3] ++ [] = [2,3]
Q [7,3,2,8] = [2,3] ++ [7] ++ [8] = [2,3,7,8]
Q [2,7,3,2,8,1] = [1] ++ [2] ++ [2,3,7,8]initial: (0,0,0,0,0,0,0,0)
read 2: (0,1,0,0,0,0,0,0)
read 7: (0,1,0,0,0,0,1,0)
read 3: (0,1,1,0,0,0,1,0)
read 2: (0,2,1,0,0,0,1,0)
read 8: (0,2,1,0,0,0,1,1)
read 1: (1,2,1,0,0,0,1,1)The cumulative counts are . For the usual stable sorting version with zero-based output indices, scan the input from right to left, place a key at position , and decrement . The successive placements are
1 at , 8 at , the later 2 at , 3 at , 7 at , and the earlier 2 at . The final answer for all three sorting algorithms isSort once by nondecreasing end time, then retain the most recent meeting:When an interval is inspected, because of the sorted end order. Therefore the interval is already covered exactly when ; otherwise it is the earliest-ending uncovered interval and the algorithm chooses its end. This proves that the scan implements greedy strategy 2. The strict test
Meetings(intervals):
sort intervals by nondecreasing end
result = []
haveMeeting = false
for (s,e) in intervals:
if not haveMeeting or s > lastMeeting:
lastMeeting = e
append e to result
haveMeeting = true
return results > lastMeeting correctly treats equality as covered for closed intervals.The sorting costs comparisons, and the scan costs , with space for the output and constant scan state. Including an empty input, the overall bound is time, conventionally for . Additional sorting space depends on the selected sorting algorithm. Part (d) proves that the returned number of meetings is minimum.
Merge sort splits the array into two halves, recursively sorts both and merges their sorted outputs. During the merge algorithm, compare the first unconsumed entry of each half, emit the smaller and advance that half; append the remainder when one half ends. The emitted prefix is always sorted and contains exactly the already consumed entries, proving the merge step correct. Induction on input length proves the full sorting algorithm correct.
The recurrence relation is for powers of two, with constant base cost. In the Master theorem, and , matching the merge term. Hence . Floor/ceiling splits give the same bound for arbitrary ; conventional merging uses auxiliary space.
The ordering operations used to decide the partitions require an
Ord a constraint. A function with parametric polymorphism and type [a] -> [a] cannot inspect arbitrary element values to decide which one is smaller; for example, functions themselves need not admit the comparison operations required by this sorting algorithm. A Haskell Ord class instance supplies the comparison method, with its ordering laws a separate semantic assumption.[ref]Haskell 2010 Language Report. Chapter 9, the Ord class and compare method
Sorting 2026-10-20
Rearranging a finite sequence according to a specified order while preserving its entries and their multiplicities. A sorting algorithm performs this operation; lexicographic order supplies a common order for tuples or strings.
Sorting algorithm 2026-10-13
A sorting algorithm rearranges a finite sequence into nondecreasing order under a chosen total order on its keys. Its output must contain every input entry exactly once, including repetitions: producing ordered values is insufficient if entries are lost. Merge sort is one such algorithm; stable sorting adds a requirement about equal keys.
Sorting creates reusable structure: equal sort keys become adjacent, and a sorted array supports binary search. However, an algorithm correctness check must establish both sortedness and sorting permutation preservation. Replacing every entry by the smallest key can produce ordered keys while destroying the original data. Stable sorting imposes a third condition when equal sort keys occur: retain their arrival order.
For example, take complete sorting records , with the first component as the sort key and the letter as associated data. A correct output is . The sort keys are ordered, every complete sorting record remains, and the equal-key pairs keep before and before . The output satisfies sortedness and sorting permutation preservation, but fails stable sorting. The output has the right multiset of sort keys but loses and duplicates ; it fails sorting permutation preservation of complete sorting records.
To express stable sorting precisely, label every input occurrence by its original position, even when two complete sorting records have identical contents. Let be the output position of the occurrence originally at position . Besides sortedness and sorting permutation preservation, requireHere is the sort key function. Sorting by the pair under lexicographic order gives the same order as stable sorting by : the original position breaks ties without discarding associated data. For a two-field ordering, first apply stable sorting by the secondary sort key, then apply stable sorting by the primary sort key. The second pass retains the secondary order within each group of equal primary sort keys. For instance, first becomes by letter, then by number.
Sorting permutation preservation 2026-10-13
The output of a sorting algorithm must be a permutation of the complete input sequence. For equal lengths , require a permutation of such thatEquivalently, the input and output have the same multiset of complete entries: each entry has the same multiplicity. Equality of the underlying sets is insufficient; and have the same set of values and the same length but different multisets. When tracking occurrences rather than contents, retain original identity labels to check that each one is moved exactly once. A swap preserves this multiset automatically; an overwrite need not.
Strict weak order 2026-10-31
An irreflexive transitive comparison whose induced incomparability relation is transitive. Incomparability is then an equivalence relation, and its classes are totally ordered by the comparison. A comparison-based sorting algorithm can treat incomparable elements as ties; a merge algorithm that takes from the left input on ties preserves stable sorting. Ordinary ordering on real numbers is an example; machine NaN values require separate handling.
Test case 2026-11-05
A test case specifies conditions, inputs, an operation to perform and the expected result or acceptance property for software testing. Its test oracle must distinguish success from failure.[ref]
unittest — Unit testing framework in the Python 3.14 documentation. opening concepts, test case and test fixture; Basic example, result assertions
Merely executing a computer program without checking an outcome supplies weaker evidence.For example, a sorting algorithm given
3,1,3 should return 1,3,3. A stronger test oracle checks both sortedness and preservation of the input multiset; checking only sortedness would accept an empty result. The test case also needs a policy for equal elements if their original order matters. Explicit preconditions and expected outcomes make a failure reproducible and help a later reader understand which contract the test case exercises. Test oracle 2026-11-05
A test oracle determines whether an observed test result is acceptable. It can be an explicitly expected output, a mathematical property, a trusted reference implementation or another justified source of comparison. Generating many inputs without an oracle does not by itself establish whether the results are correct.
For a sorting routine, an oracle can check both sortedness and preservation of the input multiset. Returning an empty sequence passes a sortedness check but fails preservation for a nonempty input. A differential test instead compares implementations; a disagreement exposes a problem without necessarily identifying which implementation is wrong. Hypothesis documents both reference-oracle comparisons and differential comparisons in its equivalence-test generator.[ref]
Integrations Reference in the Hypothesis documentation. equivalent, oracle and differential testing examples



