-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslide01-11notes.Rmd
2816 lines (2116 loc) · 87.8 KB
/
slide01-11notes.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Slide Notes: 01-11"
author: "David J. Hunter"
output:
html_document:
toc: true
toc_float:
collapsed: false
smooth_scroll: true
df_print: paged
theme: spacelab
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(comment = NA)
```
This page contains the content of all the slides for the material that we covered in Chapters 1-3 of [Algorithms](http://jeffe.cs.illinois.edu/teaching/algorithms/book/Algorithms-JeffE.pdf), by Jeff Erickson. If you notice any errors, please [create a new issue](https://github.com/djhunter/algorithms/issues).
# Introduction: Space, Time, Perfection?
## Algorithms
### What is an Algorithm?
From [our textbook](http://jeffe.cs.illinois.edu/teaching/algorithms/book/Algorithms-JeffE.pdf):
> An algorithm is an *explicit*, precise, *unambiguous*, mechanically-executable sequence of elementary instructions, usually intended to *accomplish* a specific purpose.
From \textit{Algorithms}, by Cormen, et. al. [CLRS]:
> An algorithm is any *well-defined* computational procedure that takes some value, or set of values, as input and *produces* some value, or set of values, as output.
### Example: Peasant Multiplication
```
PeasantMultiply(X, Y):
prod <- 0
x <- X
y <- Y
while x > 0
if x is odd
prod <- prod + y
x <- floor(x/2) # mediation
y <- y + y # duplation
return prod
```
- Does it work? (correctness)
- How fast is it? (time)
- How much storage does it require? (space)
## Correctness
```
PeasantMultiply(X, Y):
prod <- 0
x <- X
y <- Y
while x > 0
if x is odd
prod <- prod + y
x <- floor(x/2) # mediation
y <- y + y # duplation
return prod
```
- "Easy" to show that **`XY == prod + xy`** is an *invariant* for the while loop.
- At loop termination, **`x == 0`**, so **`prod == XY`**.
- The algorithm *correctly* computes the product of `X` and `Y`.
## Running Time
```
PeasantMultiply(X, Y):
prod <- 0
x <- X
y <- Y
while x > 0
if x is odd
prod <- prod + y
x <- floor(x/2) # mediation
y <- y + y # duplation
return prod
```
How many mediation and duplation operations does this algorithm require?
- Answer the [poll question](https://forms.gle/Phu8bX9DtAZ7wQJVA).
### Asymptotic notation (review)
- **$f(n)$ is $O(g(n))$** if $f(n)$ is **less than or equal** to a constant multiple of $g(n)$ for large $n$.
- **$f(n)$ is $\Omega(g(n))$** if $f(n)$ is **greater than or equal** to a constant multiple of $g(n)$ for large $n$.
- **$f(n)$ is $\Theta(g(n))$** if $f(n)$ is **both** $O(g(n))$ and $\Omega(g(n))$. In this case, we say that $f$ and $g$ are *asymptotically* the same.
We use big-$O$ to represent asymptotic upper bounds, and big-$\Omega$ for asymptotic lower bounds.
### Big-Theta shortcuts
- Symmetry Rule: If $f \in\Theta(g)$, then $g\in \Theta(f)$.
- Reflexivity Rule: $f \in \Theta(f)$.
- Transitivity Rule: If $f\in \Theta(g)$ and $g\in \Theta(h)$, then $f\in \Theta(h)$.
- Sum Rule: If $f\in O(g)$, then $f+g \in \Theta(g)$.
- Constant Multiple Rule: If $c>0$ is a constant, then $cf \in \Theta(f)$.
- Product Rule: If $f_1\in \Theta(g_1)$ and $f_2\in\Theta(g_2)$, then $f_1 \cdot f_2 \in \Theta(g_1 \cdot g_2)$.
### Little-oh and little-omega
- **$f(n)$ is $o(g(n))$** if $f(n)$ is $O(g(n))$ but not $\Theta(g(n))$.
- Little-$o$ gives an upper bound that is not "tight".
- Alternatively: $\displaystyle{\lim_{n\rightarrow \infty} \frac{f(n)}{g(n)} = 0}$
- **$f(n)$ is $\omega(g(n))$** if $f(n)$ is $\Omega(g(n))$ but not $\Theta(g(n))$.
- Little-$\omega$ gives a lower bound that is not "tight".
- Alternatively: $\displaystyle{\lim_{n\rightarrow \infty} \frac{f(n)}{g(n)} = \infty}$
### Join your table group
Join the *voice channel* for your group. (Video on if possible.)
```{r, echo=FALSE}
library(knitr)
roster <- c("Ethan", "Talia", "Drake", "Jack", "Andrew", "Blake", "Jordan", "Graham", "Kevin", "Logan", "Claire", "Bri", "Trevor", "James", "Kristen", "Levi", "Grace", "John", "Isaac", "Timothy", "Josiah", "Nathan")
set.seed(1112021)
n <- length(roster)
ngps <- 6
maxingp <- ceiling(n/ngps)
# just make random groups
groups <- matrix(c(roster[sample(n)],
rep("",(maxingp - (n %% maxingp)) %% maxingp)),
ncol=maxingp, byrow=FALSE)
rownames(groups) <- paste0("Table #", 1:nrow(groups))
kable(t(groups))
```
Complete the group exercise on the [Jamboard](https://jamboard.google.com/d/1VvpZH1jAEqjosSKcXtEM1Fn8XbQ9e7SUwqkm_D3T5qw/edit?usp=sharing).
### Asymptotic notation practice
For each pair of expressions $(A,B)$, indicate whether $A$ is $O,o,\Omega,\omega,$ and/or $\Theta$ of $B$. Check all boxes that apply. Put a ? where you are not sure. Here $c>1$, $\epsilon>0$, and $k\geq 1$ represent constants.
| $A$ | $B$ | $O$ | $o$ | $\Omega$ | $\omega$ | $\Theta$ |
|----------|----------|----------|----------|----------|----------|----------|
| $100n^2 + 1000n$ | $n^3$ | | | | | |
| $\log_2 n$ | $\log_c n$ | | | | | |
| $n^k$ | $c^n$ | | | | | |
| $\sqrt{n}$ | $n^{\sin n}$ | | | | | |
| $2^n$ | $2^{n/2}$ | | | | | |
| $n^{\log_2 c}$ | $c^{\log_2 n}$ | | | | | |
| $\log_2(n!)$ | $\log_2(n^n)$ | | | | | |
| $(\log_2 n)^k$ | $n^\epsilon$ | | | | | |
## Class Structure
### Daily Assignments on Canvas
- Due night before each class, 11:59pm.
- Questions posted in an RMarkdown file.
- Edit the RMarkdown file using RStudio, and write up solutions.
- Use code blocks for pseudocode.
- Use LaTeX for mathematics.
- Markdown syntax works.
- RMarkdown can also execute R code blocks.
- Knit to HTML, and upload `.html` file to Canvas.
### Class Routine
- Goal is to spend the majority of the time working in groups on problems.
- Just-in-time mini-lectures.
- Some slides, but they won't be comprehensive.
- Can start by discussing assignment that was due the night before.
### Exams and Grading
| Task | % of total |
|----------|----------|
| Daily Assignments: | 44% |
| Exams: | 3 @ 14% each |
| Final Exam: | 14% |
### Attendance
- I expect every student to attend every class during the scheduled class period.
- If you miss a significant number of classes, you will almost definitely do poorly in this class.
- I consider it excessive to miss more than three classes during the course of the semester.
- If you miss more than six classes without a valid excuse, I reserve the right to terminate you from the course with a grade of F.
### Academic integrity
- Dishonesty of any kind may result in loss of credit for the work involved and the filing of a report with the Provost’s Office.
- Major or repeated infractions may result in dismissal from the course with a grade of F.
- Be familiar with the [College’s plagiarism policy](https://www.westmont.edu/office-provost/academic-program/academic-integrity-policy).
- **Do not email, post online, or otherwise disseminate** any of the work that you do in this class.
- You may work with others on the assignments, but make sure that you type up your own answers yourself.
- You are on your honor that the work you hand in represents your own understanding.
### Course Materials on GitHub
https://djhunter.github.io/algorithms/
- Assignments and slides posted here.
- Links to syllabus and textbook.
- Also source code for everything, if you want to look at the repository.
# Recursion
## Assignment Comments, Sample Solutions
### Describe algorithms properly
- You can't analyze algorithms if you don't describe them properly.
- Make sure you read the [Canvas announcement](https://westmont.instructure.com/courses/5960/discussion_topics/28735) about this.
### $\Theta(n^3)$ songs
Basic idea:
```
for i<-1 to n
sing verse i
for j<-1 to n
sing verse j
for k<-1 to n
sing verse k
```
### $\Theta(n^3)$ songs
```
for i ← 1 to n
Sing “And I was like”
for j ← i down to 1
Sing “Baby, Baby, Baby, oooh,”
for k ← j down to 1
Sing "Baby, Baby, Baby, oooh,"
if i > 1
Sing “Thought you'd always be mine”
else Sing “Mine”
for i <- 1 to n:
for j <- 1 to n:
for k <- n down to 1:
Sing "On the j'th bookshelf in the i'th bookstore
on route to Kentucky, there were k Bibles
left to distribute. The clerk sent a lad off
to preach with one Bible."
if not the last verse:
Sing "So..."
```
### Another idea:
> Sing the twelve days of Christmas but for every type of gift, sing BottlesOfBeer(i) with i equal to how many gifts there are (e.g., instead of singing "5 golden rings", sing BottlesOfBeer(5)). Twelve days of Christmas is $\Theta(n^2)$, and bottles of beer is $\Theta(n)$ so it ends up being $\Theta(n^3)$.
Not pseudocode, but clearly defines an algorithm.
### Counting Syllables
Estimate. Don't try to count things exactly.
- 2a. $O(\log n)$: The number of syllables in $n$ is asymptotically equivalent to the number of digits in $n$, which is $O(\log n)$.
- 2b. $O(n \log n)$: For $i = 1 \ldots n$, singing $i$ requires $O(\log n)$ syllables, and $i$ gets sung $O(n)$ times.
- 2c. $O(n^2 \log n)$: (similar to 2b)
### Two-element subset sum
This **does not** specify an algorithm:
> ... merge sort the numbers in the array, and then iterate through the array and check if the sum of the number and the number after it, and lastly print the result.
- If your algorithm has a loop, write it as a loop, and explicitly describe what happens in an arbitrary iteration.
- If your algorithm is recursive, write it recursively, and explicitly describe the case boundaries and what happens in each case.
### Two-element subset sum
Acceptable answer, if not great:
```
SumFromArr(intArray, x)
for each element a in intArray
for each of the other elements b
add a to b
if sum is x, return true
return false
```
Running time is $\Theta(n^2)$
### Two-element subset sum
$\Theta(n \log n)$ examples:
```
findSumInArr(arr, x):
arr = mergeSort(arr)
leftPointer <- 0
rightPointer <- (length of arr) - 1
while (leftPointer < rightPointer) {
if ((arr[leftPointer] + arr[rightPointer]) == x)
return 1
else if ((arr[leftPointer] + arr[rightPointer]) < x)
leftPointer <- leftPointer + 1
else
rightPointer <- rightPointer - 1
}
findsum(array arr, int x) :
mergeSort arr
for a in arr:
binary search arr for (x - a)
if (x - a) is found
return true;
return false
```
## The Recursion Fairy
### Writing Recursive Functions
> Your **only** task is to simplify the original problem, or to solve it directly when simplification is either unnecessary or impossible; the *Recursion Fairy* will solve all the simpler subproblems for you, using Methods That Are None Of Your Business...
The Recursion Fairy is the inductive hypothesis.
### Recursive Peasant Multiplication
```
PeasantMultiply(X, Y):
if X = 0
return 0
else
x <- floor(X/2)
y <- Y + Y
prod <- PeasantMultiply(x, y) # Recursion Fairy does correctly
if X is odd
prod <- prod + Y
return prod
```
**Strong** inductive hypothesis:
`PeasantMultiply(x,y)` works for any `x` less than `X`.
## Time and Recurrence Relations
### {data-background="https://www.includehelp.com/data-structure-tutorial/images/tower-of-hanoi-1.png" data-background-size="contain"}
### Towers of Hanoi
```
Hanoi(n, src, dst, tmp):
if n > 0
Hanoi(n − 1, src, tmp, dst)
move disk n from src to dst
Hanoi(n − 1, tmp, dst, src)
```
### Towers of Hanoi Time
```
Hanoi(n, src, dst, tmp): # T(n) moves
if n > 0
Hanoi(n − 1, src, tmp, dst) # T(n-1) moves
move disk n from src to dst # 1 move
Hanoi(n − 1, tmp, dst, src) # T(n-1) moves
```
$$
T(n) = \left\{\begin{array}{ll}
0 & \mbox{if } n=0 \\
2T(n-1) +1 & \mbox{if } n>0
\end{array}
\right.
$$
### "Straightforward" induction proof
Suppose that $T(n)$ is given by the recurrence relation:
$$
T(n) = \left\{\begin{array}{ll}
0 & \mbox{if } n=0 \\
2T(n-1) +1 & \mbox{if } n>0
\end{array}
\right.
$$
Prove that $T(n) = 2^n - 1$ for all $n\geq 0$.
- Base case: $T(0) = 0 = 2^0 -1$. Check.
- **Strong** induction hypothesis: Suppose as inductive hypothesis that $T(k) = 2^k - 1$ for all $k < n$.
- Inductive step:
\begin{align}
T(n) &= 2T(n-1) + 1 && \mbox{by the recurrence relation} \\
&= 2(2^{n-1} - 1) + 1 && \mbox{by inductive hypothesis} \\
&= 2^n - 1
\end{align}
## Another Recursive Puzzle
### {data-background="https://i.pinimg.com/originals/9e/9d/77/9e9d773c7f91cc277708cd1b8d53357d.jpg" data-background-size="contain"}
### Abstract Description
- Puzzle is a sequence of $n$ bits.
- Starts at $111\ldots 1$. Need to make it $000\ldots 0$.
- You can always flip the rightmost bit. (i.e., bit #1)
- If $z$ is the number of 0's on the right, you can flip the $(z+2)$th bit.
Solution for $n=5$:
```
11111 -> 11110 -> 11010 -> 11011 -> 11001 -> 11000 -> 01000 -> 01001
-> 01011 -> 01010 -> 01110 -> 01111 -> 01101 -> 01100 -> 00100
-> 00101 -> 00111 -> 00110 -> 00010 -> 00011 -> 00001 -> 00000
```
### Jamboard Questions
1. Consider the case $n = 3$. Draw a graph whose nodes are the 8 possible states of the puzzle, and draw a directed edge between two states if there is a legal move between the states. Is there a directed path from 111 to 000? Is there more than one path?
2. Describe a recursive algorithm for solving this puzzle. Your input is the number of rings $n$; your algorithm should print a reduced sequence of moves that solves the puzzle. For example, given the integer 5 as input, your algorithm should print the sequence 1, 3, 1, 2, 1, 5, 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1.
### Table Groups
```{r, echo=FALSE}
library(knitr)
roster <- c("Ethan", "Talia", "Drake", "Jack", "Andrew", "Blake", "Jordan", "Graham", "Kevin", "Logan", "Claire", "Bri", "Trevor", "James", "Kristen", "Levi", "Grace", "John", "Isaac", "Timothy", "Josiah", "Nathan")
set.seed(1132021)
n <- length(roster)
ngps <- 6
maxingp <- ceiling(n/ngps)
# just make random groups
groups <- matrix(c(roster[sample(n)],
rep("",(maxingp - (n %% maxingp)) %% maxingp)),
ncol=maxingp, byrow=FALSE)
rownames(groups) <- paste0("Table #", 1:nrow(groups))
kable(t(groups))
```
# Divide and Conquer
## Assignment Comments, Sample Solutions
### More tips on describing algorithms (from pp. 11ff)
>- **Algorithms are not programs.** Please don't write code (e.g., C, Python, Java, Haskell, R, ...).
> - Use a combination of pseudocode and structured English.
> - Pseudocode uses the structure of formal programming languages to break algorithms into primitive steps.
> - The primitive steps themselves can be written using math, English, or a mixture of the two, whatever is clearest.
> - A good algorithm description is closer to what we should write in the comments of a real program than the code itself. Code is a poor medium for storytelling.
> - On the other hand, conditionals, loops, function calls, and recursion should be stated explicitly.
### Who is the audience?
>- Imagine you are writing pseudocode for a competent but skeptical programmer who is *not as clever as you are*.
> - This programmer should be able to quickly and correctly implement the algorithm in *their* favorite programming language.
>- **Goal:** include every detail necessary to fully specify the algorithm, prove its correctness, and analyze its running time.
### Baguenaudier solver
Pseudocode and English: It is clear what it's doing and *why it works*:
```
solve(n):
If n=1,
flip(1)
If n=2
flip(2)
flip(1)
else (when n>2)
solve(n-2) on the rightmost n-2 bits
flip(n), the nth bit << legal, b/c there are n-2 0's at the end >>
solve(n-2) in reverse on the rightmost n-2 bits << makes Puzzle look like 0111...111 >>
solve(n-1) on rightmost (n-1) bits
```
### Baguenaudier solver, but a little too code-y
Psuedocode only. It's correct, but it doesn't communicate as well:
```
B(int n){
if(n == 0){
print nothing
}
else if (n==1){
print 1
}
else {
B(n-2)
print n
B(n-2), but printed backwards
B(n-1)
}
}
```
### Recurrence Relation
The recurrence relation should match the algorithm:
```
solve(n):
If n=1,
flip(1)
If n=2
flip(2)
flip(1)
else (when n>2)
solve(n-2) on the rightmost n-2 bits
flip(n), the nth bit << legal, b/c there are n-2 0's at the end >>
solve(n-2) in reverse on the rightmost n-2 bits << makes Puzzle look like 0111...111 >>
solve(n-1) on rightmost (n-1) bits
```
\begin{equation}
M(n)=\begin{cases}
1 & \text{if $n=1$}.\\
2 & \text{if $n=2$}.\\
2M(n-2)+M(n-1)+1 & \text{if $n > 2$}.
\end{cases}
\end{equation}
### Another Recurrence Relation
If the algorithm is different, the recurrence is different.
```
B(int n){
if(n == 0){
print nothing
}
else if (n==1){
print 1
}
else {
B(n-2)
print n
B(n-2), but printed backwards
B(n-1)
}
}
```
\begin{equation}
M(n)=\begin{cases}
0 & \text{if $n=0$}.\\
1 & \text{if $n=1$}.\\
2M(n-2)+M(n-1)+1 & \text{if $n > 2$}.
\end{cases}
\end{equation}
### Closed-form formula from OEIS
At least two options:
$$
2^{n+1}/3 - 1/2 - (-1)^n/6
$$
or
$$
M\left(n\right) = \left\lceil2\cdot\frac{2^n-1}{3}\right\rceil
$$
The former is easier; the latter requires cases in the induction argument.
### Inductive verification
Base case: $M(1)=1=\frac{2^{2}}{3}-\frac{1}{2}-\frac{(-1)^{1}}{6}$ and $M(2)=2=\frac{2^{3}}{3}-\frac{1}{2}-\frac{(-1)^{2}}{6}$.
Suppose as inductive hypothesis that $M(k)=\frac{2^{k+1}}{3}-1/2-\frac{(-1)^{k}}{6}$ for all $k<n$.
(When in doubt, always use *strong* induction.)
### Inductive step
\begin{align}
M(n)&=2M(n-2)+M(n-1)+1\\
&=2\left(\frac{2^{n-1}}{3}-\frac{1}{2}-\frac{(-1)^{n-2}}{6} \right) + \left(\frac{2^{n}}{3}-\frac{1}{2}-\frac{(-1)^{n-1}}{6}\right)+1\\
&=\frac{2^{n}}{3}-1-\frac{2(-1)^{n-2}}{6}+\frac{2^{n}}{3}-\frac{1}{2}-\frac{(-1)^{n-1}}{6}+1\\
&=\frac{2^{n}}{3}+\frac{2^{n}}{3}-1+1-\frac{1}{2}-\frac{2(-1)^{n-2}}{6}-\frac{(-1)^{n-1}}{6}\\
&=\frac{2^{n+1}}{3}-\frac{1}{2}+\frac{2(-1)^{n-1}}{6}-\frac{(-1)^{n-1}}{6}\\
&=\frac{2^{n+1}}{3}-\frac{1}{2}+\frac{(-1)^{n-1}}{6}\\
&=\frac{2^{n+1}}{3}-\frac{1}{2}-\frac{(-1)^{n}}{6}
\end{align}
## Trust the Recursion Fairy
### Recall: Writing recursive functions
> Your **only** task is to simplify the original problem, or to solve it directly when simplification is either unnecessary or impossible; the *Recursion Fairy* will solve all the simpler subproblems for you, using Methods That Are None Of Your Business...
### Jamboard Questions
Consider the usual Towers of Hanoi puzzle (pp. 24ff) with $n$ disks and 3 pegs, numbered 0, 1, and 2. Now suppose you are forbidden to move any disk directly between peg 1 and peg 2; *every* move must involve peg 0.
1. Describe a recursive algorithm to solve this puzzle.
2. Explain why (prove that) your algorithm never moves a disk between peg 1 and peg 2. (Use a *strong* induction hypothesis.)
### Table Groups
```{r, echo=FALSE}
library(knitr)
roster <- c("Ethan", "Talia", "Drake", "Jack", "Andrew", "Blake", "Jordan", "Graham", "Kevin", "Logan", "Claire", "Bri", "Trevor", "James", "Kristen", "Levi", "Grace", "John", "Isaac", "Timothy", "Josiah", "Nathan")
set.seed(1152021)
n <- length(roster)
ngps <- 6
maxingp <- ceiling(n/ngps)
# just make random groups
groups <- matrix(c(roster[sample(n)],
rep("",(maxingp - (n %% maxingp)) %% maxingp)),
ncol=maxingp, byrow=FALSE)
rownames(groups) <- paste0("Table #", 1:nrow(groups))
kable(t(groups))
```
## Divide and Conquer
### Divide and Conquer paradigm
- When the problem domain *partitions* into smaller subproblems, the recursive paradigm is called **divide and conquer**.
- Towers of Hanoi isn't really divide and conquer.
- Binary search *is* divide and conquer. The search space partitions into two halves.
### Merge Sort
```
Merge(A[1..n], m): MergeSort(A[1..n]):
i <- 1; j <- m + 1 if n > 1
for k <- 1 to n m <- floor(n/2)
if j > n MergeSort(A[1..m])
B[k] <- A[i]; i <- i + 1 MergeSort(A[(m+1)]..m)
else if i > m Merge(A[1..n],m)
B[k] <- A[ j]; j <- j + 1
else if A[i] < A[j]
B[k] <- A[i]; i <- i + 1
else
B[k] <- A[j]; j <- j + 1
for k <- 1 to n
A[k] <- B[k]
```
### Merge Sort recurrence
```
Merge(A[1..n], m): # O(n) comparisons MergeSort(A[1..n]): # C(n) comparisons
i <- 1; j <- m + 1 if n > 1
for k <- 1 to n m <- floor(n/2)
if j > n MergeSort(A[1..m]) # C(n/2) comparisons (approx)
B[k] <- A[i]; i <- i + 1 MergeSort(A[(m+1)]..m) # C(n/2) comparisons (approx)
else if i > m Merge(A[1..n],m) # O(n) comparisons
B[k] <- A[ j]; j <- j + 1
else if A[i] < A[j]
B[k] <- A[i]; i <- i + 1
else
B[k] <- A[j]; j <- j + 1
for k <- 1 to n
A[k] <- B[k]
```
$$
C(n) = \left\{\begin{array}{ll}
0 & \mbox{if } n=1 \\
2C(n/2) + O(n) & \mbox{if } n>1
\end{array}
\right.
$$
### Merge Sort time
$$
C(n) = \left\{\begin{array}{ll}
0 & \mbox{if } n=1 \\
2C(n/2) + O(n) & \mbox{if } n>1
\end{array}
\right.
$$
As a tree, we can model $C(n)$ as:
```
O(n)
/ \
C(n/2) C(n/2)
```
Expanding recursively, we get the following *recursion tree:*
```
n
/ \
n/2 n/2
/ \ / \
n/4 n/4 n/4 n/4
/ \ / \ / \ / \
n/8 n/8 n/8 n/8 n/8 n/8 n/8 n/8
... and so on
```
### Merge Sort time
$$
C(n) = \left\{\begin{array}{ll}
0 & \mbox{if } n=1 \\
2C(n/2) + O(n) & \mbox{if } n>1
\end{array}
\right.
$$
Total up each level in the recursion tree:
```
level total
n n
/ \
n/2 n/2 n
/ \ / \
n/4 n/4 n/4 n/4 n
/ \ / \ / \ / \
n/8 n/8 n/8 n/8 n/8 n/8 n/8 n/8 n
... and so on
```
There are $\log n$ levels in this tree, so $C(n) \in O(n \log n)$.
(More to come.)
# Divide and Conquer: Sorting
## Assignment Comments, Sample Solutions
### Beware of the Jamboard solutions
- Don't uncritically copy someone else's (e.g., the Jamboard) solutions.
### Modified Hanoi Algorithm
```
Undo [operations]:
Perform move operations in both reverse order and opposite direction
Hanoi(n, temp, destination):
if n is 1:
move disk 1 from peg 0 to destination
else:
Hanoi(n-1, destination, temp)
move disk n from peg 0 to destination
Undo Hanoi(n-1, destination, temp)
Hanoi(n-1, temp, destination)
```
- Notice that the parameter list in the function header matches the parameters that are used in the function calls.
- Sometimes `destination` and `temp` need to be switched, so we can't hard code these as 0 and 1, for example.
- If you are unsure that the base case is right, check that the $n=2$ case works.
### Proof that all moves are legal
```
Undo [operations]:
Perform move operations in both reverse order and opposite direction
Hanoi(n, temp, destination):
if n is 1:
move disk 1 from peg 0 to destination
else:
Hanoi(n-1, destination, temp)
move disk n from peg 0 to destination
Undo Hanoi(n-1, destination, temp)
Hanoi(n-1, temp, destination)
```
When $n=1$, the move involves peg 0. Suppose as inductive hypothesis that `Hanoi(k, temp, destination)` returns only moves that involve peg 0, for all $k<n$. Then `Hanoi(n, temp, destination)` makes three recursive calls, which by inductive hypothesis all involve peg 0 (note that `Undo` preserves the property of involving peg 0). The additional single move made by `Hanoi(n, temp, destination)` also involves peg 0. So by induction, all moves are legal.
### Recurrence Relation
```
Undo [operations]:
Perform move operations in both reverse order and opposite direction
Hanoi(n, temp, destination): <<Source is always 0>>
if n is 1:
move disk 1 from peg 0 to destination
else:
Hanoi(n-1, destination, temp)
move disk n from peg 0 to destination
Undo Hanoi(n-1, destination, temp)
Hanoi(n-1, temp, destination)
```
$$
V(n) = \left\{\begin{array}{ll}
1 & \mbox{if } n=1 \\
3V(n-1) +1 & \mbox{if } n>1
\end{array}
\right.
$$
### Closed-form formula
$$
V(n) = \left\{\begin{array}{ll}
1 & \mbox{if } n=1 \\
3V(n-1) +1 & \mbox{if } n>1
\end{array}
\right.
$$
```
Search: seq:1,4,13,40,121,364
A003462 a(n) = (3^n - 1)/2.
```
### Inductive verification
Base Case: $V(1)=1=\frac{3^\left(1\right)-1}{2}$. Suppose as inductive hypothesis that $V(k)=\frac{3^k-1}{2}$ for all $k<n$. Using the recurrence relation,
\begin{align}
V(n)&=3V(n-1)+1 \\
&=3\left(\frac{3^\left(n-1\right)-1}{2}\right)+1 \\
&=\frac{3^n-3}{2}+1 \\
&=\frac{3^n-3}{2}+\frac{2}{2} \\
&=\frac{3^n-1}{2} \\
\end{align}
So by induction, $V(n) = \frac{3^n-1}{2}$
## Divide and Conquer
### Divide and Conquer paradigm
- When the problem domain *partitions* into smaller subproblems, the recursive paradigm is called **divide and conquer**.
- Towers of Hanoi isn't really divide and conquer.
- Binary search *is* divide and conquer. The search space partitions into two halves.
### Merge Sort
```
Merge(A[1..n], m): MergeSort(A[1..n]):
i <- 1; j <- m + 1 if n > 1
for k <- 1 to n m <- floor(n/2)
if j > n MergeSort(A[1..m])
B[k] <- A[i]; i <- i + 1 MergeSort(A[(m+1)..n)]
else if i > m Merge(A[1..n],m)
B[k] <- A[ j]; j <- j + 1
else if A[i] < A[j]
B[k] <- A[i]; i <- i + 1
else
B[k] <- A[j]; j <- j + 1
for k <- 1 to n
A[k] <- B[k]
```
`Merge` running time? (Count comparisons of list elements.)
```
-poll "What is the running time of the Merge function?" "O(log n)" "O(n)" "O(n^2)" "O(2^n)"
```
### Merge Sort recurrence
```
Merge(A[1..n], m): # O(n) comparisons MergeSort(A[1..n]): # C(n) comparisons
i <- 1; j <- m + 1 if n > 1
for k <- 1 to n m <- floor(n/2)
if j > n MergeSort(A[1..m]) # C(n/2) comparisons (approx)
B[k] <- A[i]; i <- i + 1 MergeSort(A[(m+1)..n)] # C(n/2) comparisons (approx)
else if i > m Merge(A[1..n],m) # O(n) comparisons
B[k] <- A[ j]; j <- j + 1
else if A[i] < A[j]
B[k] <- A[i]; i <- i + 1
else
B[k] <- A[j]; j <- j + 1
for k <- 1 to n
A[k] <- B[k]
```
$$
C(n) = \left\{\begin{array}{ll}
0 & \mbox{if } n=1 \\
2C(n/2) + O(n) & \mbox{if } n>1
\end{array}
\right.
$$
### Merge Sort time
$$
C(n) = \left\{\begin{array}{ll}
0 & \mbox{if } n=1 \\
2C(n/2) + O(n) & \mbox{if } n>1
\end{array}
\right.
$$
As a tree, we can model $C(n)$ as:
```
O(n)
/ \
C(n/2) C(n/2)
```
Expanding recursively, we get the following *recursion tree:*
```
n
/ \
n/2 n/2
/ \ / \
n/4 n/4 n/4 n/4
/ \ / \ / \ / \
n/8 n/8 n/8 n/8 n/8 n/8 n/8 n/8
... and so on
```
### Merge Sort time
$$
C(n) = \left\{\begin{array}{ll}
0 & \mbox{if } n=1 \\
2C(n/2) + O(n) & \mbox{if } n>1
\end{array}
\right.
$$
Total up each level in the recursion tree:
```
level total
n n
/ \
n/2 n/2 n
/ \ / \
n/4 n/4 n/4 n/4 n
/ \ / \ / \ / \
n/8 n/8 n/8 n/8 n/8 n/8 n/8 n/8 n
... and so on
```
There are $\log n$ levels in this tree, so $C(n) \in O(n \log n)$.
(More to come.)
### Aside: This is the best you can do
- Sorting a list involves figuring how how it is scrambled.
- A list of $n$ elements can be scrambled $n!$ ways.
- Using (two-way) comparisons gets us a binary decision tree.
- In order to have $n!$ leaves, we need $\log_2(n!)$ levels.
- $\log_2(n!) \in \Theta(n \log n)$
So Merge Sort is *asymptotically optimal*.
### Merge Sort Correctness
```
Merge(A[1..n], m): MergeSort(A[1..n]):
i <- 1; j <- m + 1 if n > 1
for k <- 1 to n m <- floor(n/2)
if j > n MergeSort(A[1..m])
B[k] <- A[i]; i <- i + 1 MergeSort(A[(m+1)..n)]
else if i > m Merge(A[1..n],m)
B[k] <- A[ j]; j <- j + 1
else if A[i] < A[j]
B[k] <- A[i]; i <- i + 1
else
B[k] <- A[j]; j <- j + 1
for k <- 1 to n
A[k] <- B[k]
```
- First you have to show that `Merge` is correct (see book).
- Base case: $n=1$ `MergeSort` does nothing, and list is sorted.
- Inductive hypothesis: Suppose that `MergeSort` correctly sorts a list of size $k$ when $k<n$.
- By inductive hypothesis, `MergeSort(A[1..m])` and `MergeSort(A[(m+1)..n])` both work, so `A[1..m]` and `A[(m+1)..n]` will be correctly sorted when `Merge` is called. Since `Merge` works, `Merge(A[1..n],m)` will be correctly sorted.
## QuickSort
### Partitioning an array
`Partition(A, p)` inputs an array `A` and an array index `p`.
- `A[p]` is the *pivot* element.
`Partition(A, p)` rearranges the elements of `A` so that: