Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

4. Divide and conquer: recursion trees, binary search on the answer and inversion counting

School of Engineering, Nazarbayev University

Suppose a microgrid designer asks: What is the minimum LiFePO4 battery capacity Emin⁡E_{\min} [MWh] needed to survive a 168-hour winter wind-and-solar drought with round-trip losses and inverter clipping without ever dropping below 10%10\% state of charge? Because curtailment at full charge and the reserve floor are non-smooth, history-dependent nonlinearities, there is no closed-form algebraic inverse. Yet answering the forward yes/no question, ‘Does a battery of fixed size EE survive all 168 hours?’, is a trivial 168-step loop, and survival is monotone in EE (False ... False, True ... True). Binary-searching the answer (divide_spatial.parametric_binary_search_min) solves the inverse design problem to a tolerance of 10−9 MWh10^{-9}\,\mathrm{MWh} in 41 forward simulations (Demonstration 2; the load and generation data are synthetic). This lecture covers Mental Moves #11–#12: parametric search, Master-Theorem recursion trees, mergesort_with_inversions, and unimodal golden-section search.

Learning objectives

  1. Predict recursive divide-and-conquer scaling via the Master Theorem T(N)=a T(N/b)+c NdT(N) = a\,T(N/b) + c\,N^d across leaf-dominated (a>bda > b^d), balanced (a=bda = b^d), and root-dominated (a<bda < b^d) regimes.

  2. Invert hard engineering sizing & scheduling problems into monotone yes/no feasibility checks via divide_spatial.parametric_binary_search_min and parametric_binary_search_int.

  3. Piggyback global disorder statistics (exact pairwise inversions II and Kendall τ\tau) onto O(Nlog⁡N)\mathcal{O}(N\log N) sorting using divide_spatial.mergesort_with_inversions.

  4. Minimize noisy or non-differentiable unimodal engineering cost functions without derivatives via golden-section bracket reduction.

Time: about 60 min

1. Recursion Trees & The Master Theorem T(N)=a T(N/b)+c NdT(N) = a\,T(N/b) + c\,N^d

Splitting a problem of size NN into aa subproblems of size N/bN/b with c Ndc\,N^d divide/merge work creates a tree of depth L=log⁡bNL = \log_b N. At depth ℓ∈{0,…,L}\ell \in \{0, \dots, L\}, there are aℓa^\ell nodes each doing c (N/bℓ)dc\,(N/b^\ell)^d work, so level-ℓ\ell total work is a geometric series with ratio ρ=a/bd\rho = a / b^d:

T(N)=c Nd∑ℓ=0log⁡bN(abd)ℓ  ⟹  {Θ(Nd)if a<bd (Root-dominated: geometric decay, e.g. Quickselect),Θ(Ndlog⁡N)if a=bd (Balanced levels: MergeSort, Cooley–Tukey FFT),Θ(Nlog⁡ba)if a>bd (Leaf-dominated: aL=Nlog⁡ba leaves, e.g. Karatsuba/Strassen).(1.1)T(N) = c\,N^d \sum_{\ell=0}^{\log_b N} \left(\frac{a}{b^d}\right)^\ell \implies \begin{cases} \Theta(N^d) & \text{if } a < b^d \text{ (Root-dominated: geometric decay, e.g. Quickselect)}, \\ \Theta(N^d \log N) & \text{if } a = b^d \text{ (Balanced levels: MergeSort, Cooley–Tukey FFT)}, \\ \Theta(N^{\log_b a}) & \text{if } a > b^d \text{ (Leaf-dominated: } a^L = N^{\log_b a}\text{ leaves, e.g. Karatsuba/Strassen)}. \end{cases} \tag{1.1}

Demonstration 1: Empirical verification of all three master-theorem regimes
===========================================================================
Root-dominated (a=1, b=2, d=1 -> O(N))         | Fitted p = 1.005 | Master max(d, log_b a) = 1.000
Balanced tree (a=2, b=2, d=1 -> O(N log N))    | Fitted p = 1.169 | Master max(d, log_b a) = 1.000
Karatsuba split (a=3, b=2, d=1 -> O(N^1.585))  | Fitted p = 1.607 | Master max(d, log_b a) = 1.585
Leaf-dominated (a=4, b=2, d=1 -> O(N^2))       | Fitted p = 2.005 | Master max(d, log_b a) = 2.000
<Figure size 858x462 with 1 Axes>

Figure 4.1. Work of synthetic recursions T(N)=a T(N/2)+NT(N) = a\,T(N/2) + N for a=1,2,3,4a = 1, 2, 3, 4. The fitted exponents, 1.00, 1.17, 1.61 and 2.00, follow the three regimes of the master theorem (NN, Nlog⁡NN \log N and Nlog⁡2aN^{\log_2 a}).

  • Karatsuba multiplication uses a=3a = 3 products of half-width integers instead of a=4a = 4. Removing one recursive call per split lowers the leaf exponent from log⁡24=2.000\log_2 4 = 2.000 to log⁡23=1.585\log_2 3 = 1.585, and the fitted exponent, 1.607, agrees.


2. “Binary-Searching the Answer” on Monotone Feasibility (parametric_binary_search_min)

Mental Move #11, Binary-Search the Answer on Monotone Feasibility: Whenever an optimization problem asks for the minimum capacity/budget/deadline x∗x^* such that a complex system succeeds, check whether feasibility P(x)∈{False,True}P(x) \in \{\mathrm{False}, \mathrm{True}\} is monotone (x1≤x2∧P(x1)  ⟹  P(x2)x_1 \le x_2 \land P(x_1) \implies P(x_2)). If so, maintain the bracket invariant:

P(lo)=False∧P(hi)=True,hik−lok=hi0−lo02k(2.1)P(\mathrm{lo}) = \mathrm{False} \quad \land \quad P(\mathrm{hi}) = \mathrm{True}, \qquad \mathrm{hi}_k - \mathrm{lo}_k = \frac{\mathrm{hi}_0 - \mathrm{lo}_0}{2^k} \tag{2.1}

We apply parametric_binary_search_min to size a 168-hour solar+wind island microgrid battery (with charging/discharging efficiencies ηc=ηd=0.94\eta_c = \eta_d = 0.94, full-charge curtailment, and a 10%10\% minimum reserve floor), and parametric_binary_search_int to size the minimum fleet of parallel chemical autoclaves needed to finish 28 ordered batch jobs within 48 hours.


Demonstration 2: Parametric binary search — microgrid battery sizing and autoclave fleet dispatch
=================================================================================================
Minimum microgrid battery E_min = 228.232777 MWh found in 41 forward simulations
Minimum parallel autoclave fleet K_min = 4 units (evals = 6 vs 28 linear scan)
<Figure size 880x451 with 1 Axes>

Figure 4.2. State of charge of the microgrid battery over the synthetic seven-day record. At the bisected capacity Emin⁡=228.2 MWhE_{\min} = 228.2\,\mathrm{MWh} (solid) the battery just touches the 10 % reserve (dotted) at the bottom of the calm, cloudy spell; at 0.85 Emin⁡0.85\,E_{\min} it runs empty, at 1.2 Emin⁡1.2\,E_{\min} it keeps a margin.

  • In the solid blue curve the battery sized at Emin⁡=228.2 MWhE_{\min} = 228.2\,\mathrm{MWh} just touches the 10 %10\,\% reserve floor at the bottom of the calm, cloudy spell and then recovers; a battery 10−6 MWh10^{-6}\,\mathrm{MWh} smaller fails. The bisection needed 41 simulations and no derivatives.


3. Piggybacking Global Inversions onto MergeSort (mergesort_with_inversions)

In stratified ocean/atmospheric columns (buoyancy density inversions where heavier fluid sits above lighter fluid) and sensor rank-correlation tests, an inversion is a pair of indices i<ji < j with Ai>AjA_i > A_j. Counting all (N2)\binom{N}{2} pairs takes O(N2)\mathcal{O}(N^2).

Mental Move #12, Piggyback Global Counts onto Divide-and-Conquer: During the merge step of divide_spatial.mergesort_with_inversions, both left and right halves are already sorted. Whenever left[i] > right[j], every remaining element in left[i : nl] is also strictly greater than right[j], contributing nl - i cross-inversions in a single O(1)\mathcal{O}(1) integer addition.


Demonstration 3: O(N log N) stratification disorder and inversion counting via MergeSort
========================================================================================
Sorted inversions         : 0 (exact = 0)
Reverse-sorted inversions : 7140 (exact N(N-1)/2 = 7140)
Turbulent density profile : MergeSort = 1082 vs Brute-Force = 1082 (comps = 613 vs 7140)
MergeSort empirical complexity class: O(N log N) (fitted p = 1.189)
  • At N=3,200N = 3{,}200, mergesort_with_inversions counts the inversions in 33,26533{,}265 comparisons instead of 5.12×1065.12 \times 10^6, a factor of 154 fewer. For N=106N = 10^6 the ratio estimated from Nlog⁡2NN \log_2 N is about 2.5×1042.5 \times 10^4.


What if we want to minimize a continuous cost J(D)J(D) (such as annualized pipe capital aD1.5a D^{1.5} + turbulent pumping OPEX bD−4.75b D^{-4.75} + non-differentiable V-shaped thermal expansion penalty ∣D−Dnom∣|D - D_{\mathrm{nom}}|) without derivatives? Binary search does not apply directly to values J(x)J(x) unless we compute derivatives, because J(x)J(x) goes down then up (unimodal). Golden-Section Search places interior probes at golden-ratio fractions 1−φ−1≈0.38201 - \varphi^{-1} \approx 0.3820 and φ−1≈0.6180\varphi^{-1} \approx 0.6180 (φ=1+52\varphi = \frac{1+\sqrt{5}}{2}), reusing one interior evaluation on every step to shrink the bracket by 0.6180k0.6180^k.


Demonstration 4: Golden-section unimodal optimization on non-smooth pipe total annual cost
==========================================================================================
Golden-section optimal diameter D* = 0.402569367 m (min cost = 14.355057 kUSD/yr) in 50 evals

Inside the algorithm

We inspect divide_spatial.parametric_binary_search_min and divide_spatial.mergesort_with_inversions, and implement Hoare/Dijkstra Randomized Quickselect (quickselect_kth_order_statistic), which combines Lecture 2’s 3-way partition invariant with Lecture 4’s root-dominated recursion (a=1,b≈2,d=1  ⟹  O(N)a = 1, b \approx 2, d = 1 \implies \mathcal{O}(N) expected comparisons) to find the exact median or kk-th quantile without sorting the discarded half.

Check against the library


Inside the algorithm: Parametric search, MergeSort and O(N) randomized quickselect
==================================================================================
def parametric_binary_search_min(
    predicate: Callable[[float], bool],
    lo: float,
    hi: float,
    tol: float = 1e-9,
    max_iter: int = 80,
) -> dict:
    """Binary-search the minimum real x in [lo, hi] satisfying a monotone predicate (False ... False, True ... True)."""
    if lo > hi or tol <= 0.0:
        raise ValueError("Require lo <= hi and tol > 0.")
    evals = 1
    if not predicate(float(hi)):
        return {"threshold": math.nan, "evaluations": evals, "feasible": False}
    evals += 1
    if predicate(float(lo)):
        return {"threshold": float(lo), "evaluations": evals, "feasible": True}

    left, right = float(lo), float(hi)
    for _ in range(max_iter):
        if (right - left) <= tol:
            break
        mid = 0.5 * (left + right)
        evals += 1
        if predicate(mid):
            right = mid
        else:
            left = mid
    return {"threshold": right, "evaluations": evals, "feasible": True}

def mergesort_with_inversions(values: np.ndarray) -> dict:
    """Sort 1-D array in O(N log N) via divide-and-conquer MergeSort while counting exact pairwise inversions."""
    arr = np.asarray(values, dtype=float).ravel().tolist()
    stats = [0, 0]  # [inversions, comparisons]

    def _sort(sub: list[float]) -> list[float]:
        n = len(sub)
        if n <= 1:
            return sub
        mid = n // 2
        left = _sort(sub[:mid])
        right = _sort(sub[mid:])
        merged: list[float] = []
        i = 0
        j = 0
        nl = len(left)
        nr = len(right)
        while i < nl and j < nr:
            stats[1] += 1
            if left[i] <= right[j]:
                merged.append(left[i])
                i += 1
            else:
                merged.append(right[j])
                # Every remaining element in sorted left[i:] is strictly > right[j].
                stats[0] += nl - i
                j += 1
        if i < nl:
            merged.extend(left[i:])
        if j < nr:
            merged.extend(right[j:])
        return merged

    sorted_list = _sort(arr)
    return {
        "sorted": np.array(sorted_list, dtype=float),
        "inversions": stats[0],
        "comparisons": stats[1],
    }

N = 4096 median -> Quickselect = 99.9655620645 (10,825 comps) vs MergeSort = 99.9655620645 (43,978 comps)

Exercises

Worked solutions are in 04_solutions.ipynb. The cell below the list is a short self-check to start from.

  1. Verify a result. Verify the exact identity τ=1−4 IN(N−1)\tau = 1 - \frac{4\,I}{N(N-1)} using divide_spatial.mergesort_with_inversions against O(N2)\mathcal{O}(N^2) concordant/discordant pair counting across identity (τ=+1\tau = +1), reverse (τ=−1\tau = -1), and 30 random permutations of N=80N = 80 distinct sensors.

  2. Find how it fails. Demonstrate (a) how parametric_binary_search_min fails silently on a non-monotone rotor resonance predicate A(ω)≤2.0 mmA(\omega) \le 2.0\,\mathrm{mm} over ω∈[35,100] rad/s\omega \in [35, 100]\,\mathrm{rad/s} with resonance peaks near 35 and 78 rad/s (the search misses the unsafe band around 78 rad/s), and (b) how changing <= to < in MergeSort fabricates (N2)\binom{N}{2} fake inversions on a constant sensor vector.

  3. Implement it yourself. Implement min_relay_radius_connected(coords, max_hops) using BFS from gateway station 0 inside divide_spatial.parametric_binary_search_min on constants_benchmarks.make_sensor_station_coords(n_stations=50, seed=42). Verify monotonically decreasing Rmin⁡R_{\min} across max_hops in [1, 2, 3, 4, 6, 49], cross-check against exact discrete pairwise distance binary search, and plot the 4-hop radio relay tree.


Self-check for the exercises
============================
All checks passed.