Arrays and Iteration
Reverse Array In Place
Reverse an array by walking two pointers from the ends inward, swapping the values they reference until they meet in the middle. The allocation cost is one temporary slot.
Algorithm
Canonical input arr=(1 2 3 4 5 6 7) finishes after three swaps; the
final array is [7, 6, 5, 4, 3, 2, 1].
Basic Implementation
basic.sql
.mode list
.headers off
CREATE TABLE arr(idx INTEGER PRIMARY KEY, val INTEGER);
INSERT INTO arr(idx, val) VALUES
(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7);
WITH RECURSIVE swap(left, right, n) AS (
SELECT 0, (SELECT COUNT(*) FROM arr) - 1, 0
UNION ALL
SELECT left + 1, right - 1, n + 1 FROM swap WHERE left < right
),
moves AS (
SELECT left AS pos, right AS partner FROM swap WHERE left < right
UNION ALL
SELECT right AS pos, left AS partner FROM swap WHERE left < right
),
reversed AS (
SELECT arr.idx AS idx,
CASE WHEN moves.partner IS NULL THEN arr.val
ELSE (SELECT val FROM arr a2 WHERE a2.idx = moves.partner)
END AS val
FROM arr LEFT JOIN moves ON moves.pos = arr.idx
)
SELECT '[' || GROUP_CONCAT(val, ', ') || ']'
FROM (SELECT val FROM reversed ORDER BY idx);
Complexity
- Time: O(n)
- Space: O(1)
Implementation notes
- SQL: the recursive
swapCTE generates the(left, right)pairs produced by the two-pointer walk; forn = 7it emits three pairs ((0, 6),(1, 5),(2, 4)). The middle index3is left alone because theleft < rightguard ends the recursion there. - The
movesCTE expands each swap pair into two(pos, partner)rows so a singleLEFT JOINagainstarrrewrites every participating index in one pass.reversed.valeither pulls the partner's value or, whenmoves.partner IS NULL, keeps the original slot — that is the explicit "in place" surface SQL can honour without procedural mutation. GROUP_CONCAT(val, ', ')over the orderedreversedrows produces the canonical[7, 6, 5, 4, 3, 2, 1]text exactly like the other DSA books' bracketed output.
two-pointer convergence
A `left` pointer starts at `0`, a `right` pointer at `n - 1`. Each step swaps `arr[left]` and `arr[right]`, then moves both inward until they meet.
in-place mutation
SQL has no in-place array mutation, so the swap is modeled as a set of position-partner moves computed declaratively and projected back over the original table.