Whitelist Filter: Search Algorithms Explained
Whitelist Filter: Search Algorithms Explained
S E D G E W I C K / W A Y N E S E D G E W I C K / W A Y N E
PA R T I I : A L G O R I T H M S , T H E O R Y, A N D M A C H I N E S PA R T I I : A L G O R I T H M S , T H E O R Y, A N D M A C H I N E S
Computer Searching
• Binary search
[Link]
A blacklist is a list of entities to be rejected for service. Examples: Overdrawn account % more [Link]
Spammers public class WhiteFilter alice@home
{ bob@office
A whitelist is a list of entities to be accepted for service. Examples: Account in good standing public static int search(String key, String[] a) carl@beach
dave@boat
Friends and relatives // Search method (stay tuned).
public static void main(String[] args) % more [Link]
Whitelist filter bob@office
{
• Read a list of strings from a whitelist file. In in = new In(args[0]);
carl@beach
marvin@spam
• Read strings from StdIn and write to StdOut only String[] words = [Link](); bob@office
bob@office
those in the whitelist. while (![Link]()) mallory@spam
{ dave@boat
String key = [Link](); eve@airport
Example. Email spam filter if (search(key, words) != -1) alice@home
(message contents omitted) bob@office ✓
carl@beach ✓ [Link](key);
bob@office % java WhiteFilter [Link] < [Link]
marvin@spam } bob@office
carl@beach
alice@home bob@office ✓ bob@office
} carl@beach
whitelist bob@office StdIn bob@office ✓ StdOut bob@office
} bob@office
carl@beach mallory@spam bob@office
dave@boat
dave@boat dave@boat ✓ alice@home
dave@boat
eve@airport alice@home
...
alice@home ✓
...
3 4
Alice and Bob Strawman implementation: Sequential search (first try)
i a[i]
Sequential search
0 alice oscar?
Hey, Alice. I think I'm going to
start an Internet company.
• Check each array entry 0, 1, 2, 3, ... 1 bob
Me too. I'm thinking about for match with search string.
having 1 thousand customers next 2 carlos
month and 1 million next year.
• If match found, return index of matching string.
3 carol
• If not, return 1.
We're hoping to grow even 4 craig
faster than that. 5 dave
public static int search(String key, String[] a)
Good luck! { 6 erin
BTW, you're going to need a for (int i = 0; i < [Link]; i++) 7 eve
whitelist filter. Alice
Bob if (a[i] == key) return i;
8 frank
return -1;
Yes, I know. I'm going to a
hackathon to knock it out.
} ✘Compares references, not strings! 9 mallory
10 oscar
I'm going to take a 11 peggy
few CS courses first.
12 trent
@#$%$#@@%#!!
13 walter
14 wendy
5 6
Strawman implementation: Sequential search Mathematical analysis of whitelist filter using sequential search
Generate N random strings of length L from a given alphabet Print time required for 10N searches in a whitelist of length N
5
craig
dave
6 erin
• A typical client public static int search(String key, String[] a) 7 eve oscar?
{
• Binary search for (int i = 0; i < [Link]; i++) 8 frank
if ( a[i].compareTo(key) == 0 ) return i;
• Insertion sort return -1;
9 mallory
Match found.
10 oscar
• Mergesort }
Return 10 11 peggy
• Longest repeated substring 12 trent
13 walter
14 wendy
[Link] 14
Notation. a[lo,hi) means a[lo], a[lo+1] ... a[hi-1] (does not include a[hi]).
public static int search(String key, String[] a)
{ return search(key, a, 0, [Link]); }
Search in a[lo,hi) mid = lo + (hi-lo)/2 Lower half: a[lo,mid) Upper half: a[mid+1,hi)
lo lo lo lo public static int search(String key, String[] a, int lo, int hi) lo
{
if (hi <= lo) return -1; mid
int mid = lo + (hi - lo) / 2;
mid mid mid int cmp = a[mid].compareTo(key); hi
mid+1 if (cmp > 0) return search(key, a, lo, mid);
else if (cmp < 0) return search(key, a, mid+1, hi);
else return mid;
}
hi hi hi hi
15 16
Recursion trace for binary search Mathematical analysis of binary search
i a[i]
Exact analysis for search miss for N = 2n 1 N n
public static int search(String key, String[] a) search("oscar") 0 alice
{ return search(key, a, 0, [Link]); } return search(... 10
0, 15); • Note that n = lg(N+1) ~ lgN. 15 4
1 bob
• Subarray size for 1st call is 2n 1.
7 3
public static int search(String key, String[] a, search("oscar", a, 0, 15) 2 carlos
int lo, int hi) mid = 7;
3 carol
• Subarray size for 2nd call is 2n 1 1. lgN
{ > "eve" 3 2
if (hi <= lo) return -1; 4 craig
• Subarray size for 3rd call is 2n 2 1.
return search(...
10 8, 15);
int mid = lo + (hi - lo) / 2;
5 dave • ... 1 1
int cmp = a[mid].compareTo(key); search("oscar", a, 8, 15)
if (cmp > 0) return search(key, a, lo, mid); mid = 11; 6 erin • Subarray size for nth call is 1.
Every search miss is a top-to-bottom path in this tree.
else if (cmp < 0) return search(key, a, mid+1, hi); < "peggy" 7 eve • Total # compares (one per call): n ~ lgN.
else return mid; return search(...
10 8, 10);
} 8 frank
search("oscar", a, 8, 11) Interested in
9 mallory Proposition. Binary search uses ~lg N compares for a search miss.
mid = 9; details? Take a
10 oscar
> "mallory" course in
return search(...
10 10, 11); 11 peggy
Proof. An (easy) exercise in discrete math. algorithms.
12 trent OK!
search("oscar", a, 10, 11)
mid = 10; 13 walter
Proposition. Binary search uses ~lg N compares for a random search hit.
== "oscar"
14 wendy
return 10; Proof. A slightly more difficult exercise in discrete math.
17 18
Will scale.
19 [Link]
COMPUTER SCIENCE Sorting: Rearrange N items to put them in ascending order
S E D G E W I C K / W A Y N E
PA R T I I : A L G O R I T H M S , T H E O R Y, A N D M A C H I N E S 0 wendy 0 alice
Applications
1 alice 1 bob
• Binary search
2 dave 2 carlos
• Statistics
3 walter 3 carol
• Databases
4 carlos 4 craig
• Data compression
eve peggy
• Insertion sort
10 10
11 trent 11 trent
• Mergesort 12 bob 12 trudy
14 frank 14 walter
15 victor 15 wendy
[Link] 22
0 wendy
Q. What’s the most efficient way to sort 1 million 32-bit integers?
Insertion sort 1 alice
• Move down through the array. 2 dave
• Each item bubbles up above the larger ones above it. 3 walter
• Everything above the current item is in order. 4 carlos
• Everything below the current item is untouched. 5 carol
6 erin
7 oscar
10 eve
11 trent
12 bob
13 craig
14 frank
15 victor
23 24
Insertion sort trace Insertion sort: Java implementation
0 wendy alice alice alice alice alice alice alice alice alice alice alice alice alice alice alice
public class Insertion
1 alice wendy dave dave carlos carlos carlos carlos carlos carlos carlos carlos bob bob bob bob {
% more [Link]
2 dave dave wendy walter dave carol carol carol carol carol carol carol carlos carlos carlos carlos public static void sort(String[] a) wendy
{ alice
3 walter walter walter wendy walter dave dave dave dave dave dave dave carol carol carol carol int N = [Link]; dave % java Insertion < [Link]
4 carlos carlos carlos carlos wendy walter erin erin erin erin erin erin dave craig craig craig for (int i = 1; i < N; i++) walter alice
for (int j = i; j > 0; j--) carlos bob
5 carol carol carol carol carol wendy walter oscar oscar oscar eve eve erin dave dave dave if (a[j-1].compareTo(a[j]) > 0) carol carlos
exch(a, j-1, j); erin carol
6 erin erin erin erin erin erin wendy walter peggy peggy oscar oscar eve erin erin erin oscar
else break; craig
7 oscar oscar oscar oscar oscar oscar oscar wendy walter trudy peggy peggy oscar eve eve eve peggy
} dave
trudy erin
8 peggy peggy peggy peggy peggy peggy peggy peggy wendy walter trudy trent peggy oscar frank frank eve eve
private static void exch(String[] a, int i, int j) trent frank
9 trudy trudy trudy trudy trudy trudy trudy trudy trudy wendy walter trudy trent peggy oscar oscar { String t = a[i]; a[i] = a[j]; a[j] = t; } bob oscar
craig
10 eve eve eve eve eve eve eve eve eve eve wendy walter trudy trent peggy peggy peggy
public static void main(String[] args) frank trent
11 trent trent trent trent trent trent trent trent trent trent trent wendy walter trudy trent trent { victor trudy
String[] a = [Link](); victor
12 bob bob bob bob bob bob bob bob bob bob bob bob wendy walter trudy trudy
sort(a); walter
13 craig craig craig craig craig craig craig craig craig craig craig craig craig wendy walter victor for (int i = 0; i < [Link]; i++) wendy
[Link](a[i]);
14 frank frank frank frank frank frank frank frank frank frank frank frank frank frank wendy walter
}
15 victor victor victor victor victor victor victor victor victor victor victor victor victor victor victor wendy }
25 26
TN Moore's law. The number of transistors in an integrated circuit doubles about every 2 years.
N TN/TN/2 % java Generator 20000 ...
Sort random strings (seconds)
1 seconds
• Array of length N. 20,000 1
% java Generator 40000 ...
4 seconds
• 10-character strings. % java Generator 80000 ...
Implications
40,000 4 35 seconds
80,000 35 9
% java Generator 160000 ... • Memory size doubles every two years.
225 seconds
% java Generator 320000 ... • Processor speed doubles every two years.
160,000 225 6.4 1019 seconds
Gordon Moore
320,000 1019 4.5 ... = 10 a-z | java Insertion Founder of Intel
1929 –
a-z = abcdefghijklmnopqrstuvwxyz
...
computer instructions per second words of memory
1.28 million 14400 4 4 hours
PDP-9 tens of thousands tens of thousands
Sedgewick's rule of thumb. It
And 4x64/24 = 10+ days to
sort 10 million? Sounds bad. VAX 11-780 millions millions
Confirms hypothesis that order of growth is N 2. takes a few seconds to access
every word in a computer. CRAY 1 tens of millions tens of millions
will NOT scale Do you have
anything better?
MacBook Air billions billions
27 28
Scalability COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
An algorithm scales if its running time doubles when the problem size doubles. PA R T I : P R O G R A M M I N G I N J AVA
2x faster computer with 2x memory using an alg that scales? Image sources
• Can solve problems we're solving now in half the time. order of [Link]
scales?
growth
• Can solve a 2x-sized problem in the same time it took to
solve an x-sized problem. N ✓
• Progress.
N log N ✓
2x faster computer with 2x memory using quadratic alg? N2 ✗
• Can solve problems we're solving now in half the time.
• Takes twice as long solve a 2x-sized problem as it took to N3 ✗
solve an x-sized problem.
• Frustration.
Bottom line. Need algorithms that scale to keep pace with Moore's law.
29 [Link]
•mid,
Useint hi)
auxiliary array for result. carol • Recursively sort each half. wendy
{ alice
• Copy backa[lo,
// Merge when merge
mid) with is complete.
a[mid, hi) into aux[0, dave • Merge two halves to make sorted whole. dave % java Merge < [Link]
hi-lo). walter
erin alice
int i = lo, j = mid, N = hi - lo; carlos bob
for (int k = 0; k < N; k++) oscar public class Merge carol carlos
{ { erin carol
if (i == mid) aux[k] = a[j++]; walter private static String[] aux; oscar craig
else if (j == hi) aux[k] = a[i++]; public static void merge(String[] a, int lo, int mid, int hi) peggy
wendy { // See previous slide. }
dave
else if (a[j].compareTo(a[i]) < 0) aux[k] = trudy erin
a[j++]; j bob mid public static void sort(String[] a) eve eve
{ trent
else aux[k] = aux = new String[[Link]]; // Allocate just once! frank
craig bob
a[i++]; sort(a, 0, [Link]); oscar
} eve } craig peggy
// Copy back into a[lo, hi) public static void sort(String[] a, int lo, int hi) frank trent
for (int k = 0; k < N; k++) frank { // Sort a[lo, hi). victor trudy
a[lo + k] = aux[k]; int N = hi - lo; victor
peggy
} if (N <= 1) return; walter
trent int mid = lo + N/2; wendy
sort(a, lo, mid);
trudy sort(a, mid, hi);
merge(a, lo, mid, hi);
victor
}
hi 33 ... same test client as for Insertion 34
lgN
Mergesort wendy
alice wendy
alice wendy
alice wendy
alice wendy Cost model. Count data moves.
• Divide array into two halves. alice
bob alice
carlos alice
dave alice
wendy alice
# of times a string moves
alice alice alice alice wendy
bob carlos dave wendy alice
• Recursively sort each half. dave
carlos dave
carol dave
walter dave
dave dave from one array to another
carlos carol walter dave
dave
• Merge two halves to make walter
carol walter
dave walter
wendy walter
walter walter
Exact analysis for N = 2n . carol dave wendy walter walter
sorted whole. carlos
craig carlos
erin carlos
carlos carlos
carlos carlos craig erin carlos carlos carlos
• Note that n = lgN.
carol
dave carol
oscar carol
carol carol
carol carol dave oscar carol carol carol
• 1 subarray of size 2n .
erin walter erin erin erin
erin
erin erin
walter erin
erin erin
erin erin
• 2 subarrays of size 2n 1. eve wendy oscar oscar oscar
oscar oscar oscar oscar oscar
eve wendy oscar oscar • 4 subarrays of size 2n 2. frank bob eve peggy peggy
peggy
frank peggy
bob peggy
eve peggy
peggy peggy • ... oscar craig peggy trudy trudy
trudy
oscar trudy
craig trudy
peggy trudy
trudy trudy • 2n subarrays of size 1. peggy eve trent eve eve
trent frank trudy trent trent
eve
peggy eve
eve eve
trent eve
eve eve • Total # data moves: 2N lgN.
trudy peggy bob bob bob
trent
trent trent
frank trent
trudy trent
trent trent
victor trent craig craig craig
bob
trudy bob
peggy bob
bob bob
bob bob walter trudy frank frank frank
Interested in
craig
victor craig
trent craig
craig craig
craig craig wendy victor victor victor victor
details? Take a
frank frank frank frank frank course in 1 subarray 2 subarrays 4 subarrays 8 subarrays 16 subarrays
walter trudy frank frank of size N of size N/2 of size N/4 of size N/8 of size N/16
victor victor victor victor victor algorithms.
wendy victor victor victor 2N data moves 2N data moves 2N data moves 2N data moves
35 36
Empirical tests of mergesort COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
TN
N TN/TN/2 % java Generator 1000000 ...
Sort random strings (seconds)
1 seconds
• Array of length N. 1 million 1
% java Generator 2000000 ...
2 seconds
• 10-character strings. % java Generator 4000000 ...
2 million 2 5 seconds
% java Generator 8000000 ...
4 million 5 2.5 10 seconds
% java Generator 16000000 ...
8 million 10 2 20 seconds
20
minutes OK! Let's get started...
• A typical client
Example 2. a a c a a g t t t a c a a g t t t a c a a g c t a g c
• Binary search
• Insertion sort 3 . 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4
Example 3 (first 100 digits of π). 6 2 6 4 3 3 8 3 2 7 9 5 0 2 8 8 4 1 9 7
• Mergesort
1 6 9 3 9 9 3 7 5 1 0 5 8 2 0 9 7 4 9 4
• Longest repeated substring
4 5 9 2 3 0 7 8 1 6 4 0 6 2 8 6 2 0 8 9
9 8 6 2 8 0 3 4 8 2 5 3 4 2 1 1 7 0 6 9
[Link] 40
LRS example: repetitive structure in music LRS applications
Analysts seek repeated sequences in real-world data because they are causal.
3.141592653589793238462643383279502884
Example 1: Digits of π 19716939937510582097494459230781640628
62089986280348253421170679821480865132
Mary had a little lamb • Q. Are they “random” ? 82306647093844609550582231725359408128
48111745028410270193852110555964462294
• A. No, but we can’t tell the difference. 89549303819644288109756659334461284756
48233786783165271201909145648566923460
• Ex. Length of LRS in first 10 million digits is 14. 34861045432664821339360726024914127372
45870066063155881748815209209628292540
Doubling x10
% java Generator 1 10000 actg | java LRS
N TN TN/TN/2 N TN TN/TN/10 Exception in thread "main" [Link]: Java heap space
at [Link]([Link])
2,000,000 3 1,000,000 2 at [Link].<init>([Link])
at [Link]([Link])
4,000,000 7 2.3 10,000,000 21 10 at [Link]([Link])
at [Link]([Link])
8,000,000 16 2.3
16,000,000 39 2.4
Confirms hypothesis that the order of growth is N log N (for the sort).
Bottom line. Scales with the size of the input and enables new research and development. Change in the system breaks a working program (not good).
47 48
Explanation: Two alternatives for implementing substrings Fixing the LRS implementation
• Linear time algorithm (guarantee) is known. Hey, Bob. Our IPO is next week!
51 52
COMPUTER SCIENCE COMPUTER SCIENCE
S E D G E W I C K / W A Y N E S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA PA R T I I : A L G O R I T H M S , T H E O R Y, A N D M A C H I N E S
Image sources
[Link]
Computer Science
11. Sorting and
Computer Searching
ScienceAn Interdisciplinary Approach
ROBERT SEDGEWICK
[Link]
[Link]