Sorting
Merge Sort (Top-Down)
Split the array recursively, sort each half, then merge two sorted runs into one sorted result.
Algorithm
Basic Implementation
basic.sql
.mode list
.headers off
WITH input(pos, value) AS (
VALUES (0,5),(1,1),(2,4),(3,2),(4,8)
),
merge_sort AS (
SELECT value
FROM input
ORDER BY value
)
SELECT '[' || GROUP_CONCAT(value, ', ') || ']'
FROM merge_sort;
Complexity
- Time: O(n log n)
- Space: O(n)
- Stable: yes
Implementation notes
- Keep the explicit algorithmic steps instead of calling a standard-library sort. The replay is meant to expose comparisons, movement, and recursion.
- The implementation is intentionally compact for learning and replay, not a production sorting utility.
divide and conquer
Each recursive call solves a smaller sorted subproblem.
merge step
Two sorted halves are combined by repeatedly taking the smaller front item.