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 swap CTE generates the (left, right) pairs produced by the two-pointer walk; for n = 7 it emits three pairs ((0, 6), (1, 5), (2, 4)). The middle index 3 is left alone because the left < right guard ends the recursion there.
  • The moves CTE expands each swap pair into two (pos, partner) rows so a single LEFT JOIN against arr rewrites every participating index in one pass. reversed.val either pulls the partner's value or, when moves.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 ordered reversed rows 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.