TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › Testing Sortedness and Monotonicity

Testing Sortedness and Monotonicity

Is an array of nn numbers sorted? Reading it takes nn queries, and no algorithm can be sure with fewer, since a single out-of-place element changes the answer. A property tester only has to reject arrays that are ε\varepsilon-far from sorted, that is, arrays in which at least εn\varepsilon n entries must change to make them sorted. The previous lesson showed that checking random adjacent pairs does not work. The tester of Ergün, Kannan, Kumar, Rubinfeld and Viswanathan (2000) uses binary search instead and needs only O(log⁡n/ε)O(\log n / \varepsilon) queries, which is optimal. The second half of the lesson tests monotonicity of Boolean functions on the hypercube, the same property in many dimensions.

The binary-search tester

Assume first that the entries are distinct. Pick a random index ii and run an ordinary binary search for the value aia_i in the array, as if it were sorted. In a sorted array the search ends at position ii. Call ii good if it does, and bad otherwise.

text
Sortedness tester (Ergün et al., 2000)
1  repeat ⌈2/ε⌉ times:
2      i ← a uniformly random index
3      binary search for a[i] in a[1..n]  (comparing with the probed entries as if a were sorted)
4      if the search does not end at position i: reject
5  accept

Repeated values are handled by searching for the pair (ai,i)(a_i, i) under lexicographic order, which makes the keys distinct without changing which arrays are sorted.

Lemma. The good indices, in increasing order, carry increasing values. Hence if aa is ε\varepsilon-far from sorted, at least εn\varepsilon n indices are bad.

Proof. Take good indices i<ji < j. Their binary searches start at the same midpoint and follow the same path as long as the probed position separates neither; let kk be the last probe they share, after which they go different ways. Since the search for aia_i ends at ii and the one for aja_j at jj, with i<ji < j, the search for aia_i went left (or stopped) at kk and the one for aja_j went right (or stopped): ai≤ak≤aja_i \le a_k \le a_j, with at least one inequality strict, so ai<aja_i < a_j. Thus the good indices form a sorted subsequence, and changing every bad entry (for example to the value of the nearest good entry to its left) sorts the array. If fewer than εn\varepsilon n indices were bad, the array would be ε\varepsilon-close. □\square

Theorem (Ergün et al., 2000). The tester always accepts a sorted array, rejects an ε\varepsilon-far array with probability at least 1−(1−ε)2/ε≥1−e−21 - (1 - \varepsilon)^{2/\varepsilon} \ge 1 - e^{-2}, and makes O(log⁡n/ε)O(\log n / \varepsilon) queries. Any tester needs Ω(log⁡n/ε)\Omega(\log n / \varepsilon) queries (Ergün et al. for non-adaptive testers with one-sided error, Fischer, 2004, in general).

The program runs the tester with ε=0.1\varepsilon = 0.1 on arrays of length 10 000 and compares the fraction of bad indices with the true distance (computed from a longest non-decreasing subsequence).

python · try it yourself
import bisect, math, random

def distance_to_sorted(a):
    tails = []
    for v in a:
        i = bisect.bisect_right(tails, v)
        if i == len(tails): tails.append(v)
        else: tails[i] = v
    return 1 - len(tails) / len(a)

def search_ok(a, i):
    """Binary search for the key (a[i], i) in a, treating a as sorted by (value, index); True if it ends at i."""
    key = (a[i], i)
    lo, hi, queries = 0, len(a) - 1, 1                 # a[i] itself was queried
    while lo <= hi:
        mid = (lo + hi) // 2
        queries += 1
        k = (a[mid], mid)
        if k == key:
            return True, queries
        if k < key:
            lo = mid + 1
        else:
            hi = mid - 1
    return False, queries

def sortedness_tester(a, eps, rng):
    total = 0
    for _ in range(math.ceil(2 / eps)):
        ok, q = search_ok(a, rng.randrange(len(a)))
        total += q
        if not ok:
            return False, total
    return True, total

rng = random.Random(2000)
n, eps = 10000, 0.1
b = list(range(n))
for _ in range(n // 40):
    i, j = rng.randrange(n), rng.randrange(n)
    b[i], b[j] = b[j], b[i]
c = list(range(n))
for i in range(0, n - 10, 10):                          # 10% of positions spoiled locally
    c[i], c[i + 5] = c[i + 5], c[i]
inputs = {"sorted": list(range(n)), "two sorted halves swapped": list(range(n // 2, n)) + list(range(n // 2)),
          "sorted, then 5% random swaps": b, "in each block of 10, 1st and 6th swapped": c,
          "random permutation": rng.sample(range(n), n)}
print(f"n = {n}, eps = {eps}: {math.ceil(2 / eps)} binary searches of about log2 n = {math.log2(n):.1f} queries")
print("input                                    distance   bad indices   rejection rate   queries per run")
for name, a in inputs.items():
    bad = sum(not search_ok(a, i)[0] for i in range(n)) / n
    runs = [sortedness_tester(a, eps, rng) for _ in range(300)]
    rej = sum(not ok for ok, _ in runs) / len(runs)
    q = sum(t for _, t in runs) / len(runs)
    print(f"{name:40} {distance_to_sorted(a):8.3f}   {bad:11.3f}   {rej:14.3f}   {q:15.1f}")
n = 10000, eps = 0.1: 20 binary searches of about log2 n = 13.3 queries
input                                    distance   bad indices   rejection rate   queries per run
sorted                                      0.000         0.000            0.000             267.0
two sorted halves swapped                   0.500         0.500            1.000              26.3
sorted, then 5% random swaps                0.049         0.389            1.000              35.9
in each block of 10, 1st and 6th swapped    0.200         0.338            1.000              39.8
random permutation                          0.981         0.999            1.000              14.2

The fraction of bad indices is always at least the distance, as the lemma says, and often far more: a random 5% of swaps spoils 39% of the binary searches, because one misplaced element misdirects every search whose path probes it. The tester spends about 20 searches of 13 to 14 probes on a sorted array and stops early otherwise.

In C++

The same tester on an array of 2222^{22} entries with repeated values (each value three times), using (ai,i)(a_i, i) keys. About 880 queries decide an array of four million entries, with ε=0.05\varepsilon = 0.05.

cpp · try it yourself
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <random>
#include <utility>
#include <vector>

struct Result { bool accept; long queries; };

// Binary-search tester (Ergun, Kannan, Kumar, Rubinfeld and Viswanathan, 2000).
// Keys are (value, index) pairs, so repeated values are handled too.
Result test_sorted(const std::vector<int>& a, double eps, std::mt19937_64& rng) {
    long queries = 0;
    int trials = (int)std::ceil(2 / eps);
    for (int t = 0; t < trials; ++t) {
        std::size_t i = rng() % a.size();
        std::pair<int, std::size_t> key{a[i], i};
        ++queries;
        std::size_t lo = 0, hi = a.size();                 // search in [lo, hi)
        bool found = false;
        while (lo < hi) {
            std::size_t mid = lo + (hi - lo) / 2;
            ++queries;
            std::pair<int, std::size_t> k{a[mid], mid};
            if (k == key) { found = true; break; }
            if (k < key) lo = mid + 1; else hi = mid;
        }
        if (!found) return {false, queries};               // the search path is inconsistent
    }
    return {true, queries};
}

int main() {
    const std::size_t n = 1 << 22;                          // about 4 million entries
    std::mt19937_64 rng(2000);
    std::vector<int> a(n);
    for (std::size_t i = 0; i < n; ++i) a[i] = int(i / 3);  // sorted, with repeated values
    auto show = [&](const char* name) {
        int rejected = 0; long q = 0;
        for (int r = 0; r < 200; ++r) { auto res = test_sorted(a, 0.05, rng); rejected += !res.accept; q += res.queries; }
        std::printf("%-34s rejected %3d of 200 runs, %6.1f queries per run\n", name, rejected, q / 200.0);
    };
    show("sorted (n = 2^22)");
    for (std::size_t i = 0; i < n; i += 16) std::swap(a[i], a[i + 8]);   // 1/8 of the entries displaced
    show("every 16th entry swapped ahead");
    for (std::size_t i = 0; i < n; i += 16) std::swap(a[i], a[i + 8]);   // undo
    std::swap(a[n / 2], a[n / 2 + 1000]);                  // a single out-of-order pair
    show("sorted except one swapped pair");
}
sorted (n = 2^22)                  rejected   0 of 200 runs,  879.3 queries per run
every 16th entry swapped ahead     rejected 200 of 200 runs,   43.9 queries per run
sorted except one swapped pair     rejected   1 of 200 runs,  878.3 queries per run

A single swapped pair is only 2/n2/n-far from sorted, and the tester is allowed to accept it; it noticed it once in 200 runs, when it happened to search for one of the two entries.

Monotonicity on the hypercube

A function f:{0,1}d→{0,1}f : \{0,1\}^d \to \{0,1\} is monotone if x≤yx \le y coordinate-wise implies f(x)≤f(y)f(x) \le f(y). Sortedness is the one-dimensional case on a line; here the domain is the dd-dimensional cube with n=2dn = 2^d points, and distance counts the fraction of the 2d2^d values that must change.

The edge tester (Goldreich, Goldwasser, Lehman, Ron and Samorodnitsky, 2000): pick a random edge of the cube, a pair (x,x+ei)(x, x + e_i) with xi=0x_i = 0, and reject if f(x)>f(x+ei)f(x) > f(x + e_i). Repeat O(d/ε)O(d/\varepsilon) times.

Theorem (Goldreich et al., 2000). If ff is ε\varepsilon-far from monotone, at least an ε/d\varepsilon/d fraction of the d 2d−1d\,2^{d-1} edges are violated. Hence the edge tester with O(d/ε)O(d/\varepsilon) queries rejects ε\varepsilon-far functions with probability at least 23\frac{2}{3}, and it never rejects a monotone function.

Idea of the proof. Fix the violated edges one direction at a time with a switching operator: in direction ii, swap the values of f(x)f(x) and f(x+ei)f(x + e_i) on every violated edge of that direction. One shows that switching in direction ii does not increase the number of violated edges in any other direction, so after all dd directions ff is monotone, and the number of values changed is at most twice the number of violated edges. So ε 2d≤2⋅(violated edges)\varepsilon\, 2^d \le 2 \cdot (\text{violated edges}), which is the claim.

python · try it yourself
import math, random
from itertools import product

d = 10
cube = list(range(1 << d))
def violated_edge_fraction(f):
    """Fraction of hypercube edges x -> x + e_i (bit i from 0 to 1) with f(x) > f(x + e_i)."""
    bad = sum(f[x] > f[x | 1 << i] for x in cube for i in range(d) if not x >> i & 1)
    return bad / (d * (1 << (d - 1)))

def edge_tester(f, eps, rng):
    for _ in range(math.ceil(2 * d / eps)):
        x, i = rng.randrange(1 << d), rng.randrange(d)
        x &= ~(1 << i)                              # lower end of a random edge in direction i
        if f[x] > f[x | 1 << i]:
            return False
    return True

rng = random.Random(2000)
maj = [int(bin(x).count("1") > d // 2) for x in cube]                 # monotone
anti = [1 - (x & 1) for x in cube]                                      # anti-dictator: 1/2-far
noisy = [v ^ (rng.random() < 0.05) for v in maj]                        # majority with 5% of values flipped
mixed = [((x & 1) and bin(x).count("1") > 4) or (not x & 1 and bin(x).count("1") < 4) for x in cube]
funcs = {"majority (monotone)": maj, "anti-dictator 1 - x_1 (1/2-far)": anti,
         "majority, 5% of values flipped": noisy, "mixed threshold": [int(v) for v in mixed]}
eps = 0.1
print(f"d = {d}: {d * 2 ** (d - 1)} edges; edge tester with {math.ceil(2 * d / eps)} edges for eps = {eps}")
print("function                           violated edges   rejection rate (500 runs)")
for name, f in funcs.items():
    rej = sum(not edge_tester(f, eps, rng) for _ in range(500)) / 500
    print(f"{name:34} {violated_edge_fraction(f):14.4f}   {rej:.3f}")
print(f"lemma: eps-far implies at least eps/d = {eps / d} of the edges are violated")
d = 10: 5120 edges; edge tester with 200 edges for eps = 0.1
function                           violated edges   rejection rate (500 runs)
majority (monotone)                        0.0000   0.000
anti-dictator 1 - x_1 (1/2-far)            0.1000   1.000
majority, 5% of values flipped             0.0314   0.998
mixed threshold                            0.1238   1.000
lemma: eps-far implies at least eps/d = 0.01 of the edges are violated

Every non-monotone function here has far more violated edges than the guaranteed ε/d\varepsilon/d; the anti-dictator meets the bound with a factor of 10 to spare, since all 2d−12^{d-1} edges in direction 1 are violated, a 1/d1/d fraction.

Beyond O(d/ε)O(d/\varepsilon). The edge tester's dependence on dd is not optimal. Khot, Minzer and Safra (2015) proved a directed isoperimetric inequality (a directed analogue of Talagrand's) that gives a tester with O~(d/ε2)\tilde O(\sqrt{d}/\varepsilon^2) queries, which is optimal up to polylogarithmic factors for non-adaptive testers. For functions with larger ranges or on grids [n]d[n]^d, testers with O(dlog⁡n/ε)O(d \log n/\varepsilon) queries exist (Chakrabarty and Seshadhri, 2013), generalizing both results of this lesson.

Test yourself

In the binary-search tester, when is an index ii called good?

  1. When aia_i is small
  2. When a binary search for aia_i (as if the array were sorted) ends at position ii
  3. When ai≤ai+1a_i \le a_{i+1}
  4. When ii is even

Why does an ε\varepsilon-far array have at least εn\varepsilon n bad indices?

  1. By Markov's inequality
  2. Because the good indices already form a sorted subsequence, so changing only the bad entries sorts the array; fewer than εn\varepsilon n bad indices would make it ε\varepsilon-close
  3. Because binary search is deterministic
  4. Because nn is a power of two

How many queries does sortedness testing need?

  1. O(1/ε)O(1/\varepsilon)
  2. Θ(log⁡n/ε)\Theta(\log n / \varepsilon)
  3. Θ(n)\Theta(\sqrt{n})
  4. Θ(n)\Theta(n)

What does the edge tester for monotonicity of f:{0,1}d→{0,1}f : \{0,1\}^d \to \{0,1\} check, and how many times?

  1. Random pairs of points, O(1/ε)O(1/\varepsilon) times
  2. Random hypercube edges (x,x+ei)(x, x + e_i) for f(x)>f(x+ei)f(x) > f(x + e_i), O(d/ε)O(d/\varepsilon) times
  3. All edges
  4. Random points against the all-ones point