Testing Sortedness and Monotonicity
Is an array of numbers sorted? Reading it takes 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 -far from sorted, that is, arrays in which at least 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 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 and run an ordinary binary search for the value in the array, as if it were sorted. In a sorted array the search ends at position . Call good if it does, and bad otherwise.
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 acceptRepeated values are handled by searching for the pair 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 is -far from sorted, at least indices are bad.
Proof. Take good indices . Their binary searches start at the same midpoint and follow the same path as long as the probed position separates neither; let be the last probe they share, after which they go different ways. Since the search for ends at and the one for at , with , the search for went left (or stopped) at and the one for went right (or stopped): , with at least one inequality strict, so . 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 indices were bad, the array would be -close.
Theorem (Ergün et al., 2000). The tester always accepts a sorted array, rejects an -far array with probability at least , and makes queries. Any tester needs queries (Ergün et al. for non-adaptive testers with one-sided error, Fischer, 2004, in general).
The program runs the tester with on arrays of length 10 000 and compares the fraction of bad indices with the true distance (computed from a longest non-decreasing subsequence).
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 entries with repeated values (each value three times), using keys. About 880 queries decide an array of four million entries, with .
#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 -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 is monotone if coordinate-wise implies . Sortedness is the one-dimensional case on a line; here the domain is the -dimensional cube with points, and distance counts the fraction of the values that must change.
The edge tester (Goldreich, Goldwasser, Lehman, Ron and Samorodnitsky, 2000): pick a random edge of the cube, a pair with , and reject if . Repeat times.
Theorem (Goldreich et al., 2000). If is -far from monotone, at least an fraction of the edges are violated. Hence the edge tester with queries rejects -far functions with probability at least , 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 , swap the values of and on every violated edge of that direction. One shows that switching in direction does not increase the number of violated edges in any other direction, so after all directions is monotone, and the number of values changed is at most twice the number of violated edges. So , which is the claim.
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 ; the anti-dictator meets the bound with a factor of 10 to spare, since all edges in direction 1 are violated, a fraction.
Beyond . The edge tester's dependence on is not optimal. Khot, Minzer and Safra (2015) proved a directed isoperimetric inequality (a directed analogue of Talagrand's) that gives a tester with queries, which is optimal up to polylogarithmic factors for non-adaptive testers. For functions with larger ranges or on grids , testers with queries exist (Chakrabarty and Seshadhri, 2013), generalizing both results of this lesson.
Test yourself
In the binary-search tester, when is an index called good?
- When is small
- When a binary search for (as if the array were sorted) ends at position
- When
- When is even
Why does an -far array have at least bad indices?
- By Markov's inequality
- Because the good indices already form a sorted subsequence, so changing only the bad entries sorts the array; fewer than bad indices would make it -close
- Because binary search is deterministic
- Because is a power of two
How many queries does sortedness testing need?
What does the edge tester for monotonicity of check, and how many times?
- Random pairs of points, times
- Random hypercube edges for , times
- All edges
- Random points against the all-ones point