-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlgorithms.tex
3840 lines (2352 loc) · 111 KB
/
Algorithms.tex
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
%%%%%%%%%%%%%%% LaTeX Compiler: XeLaTeX %%%%%%%%%%%%%%%
% License for LaTeX Configuration File
% This LaTeX configuration file is created by Lin, Xuanyu, HKUST, and is provided under the terms of the MIT License. You are free to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of this configuration file, subject to the following conditions:
% 1. The above copyright notice and this license notice shall be included in all copies or substantial portions of the configuration file.
% 2. The configuration file is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the configuration file or the use or other dealings in the configuration file.
% By using this configuration file, you agree to the terms and conditions of this license. If you do not agree to these terms and conditions, you must not use the configuration file.
\documentclass[10pt]{article}
% Text setting
% \usepackage{newtxtext}
\usepackage{setspace}
\usepackage[dvipsnames,svgnames]{xcolor}
\usepackage{comment}
% Chinese characters setup
\usepackage{fontspec}
\usepackage{xeCJK}
\setCJKmainfont{SimSun}
% Dealing with special characters
\usepackage[utf8]{inputenc}
% \usepackage[T1]{fontenc} % Conflict with fontspec & xeCJK
\usepackage{pifont}
% Mathematical formula typesetting
\usepackage{unicode-math}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amsthm}
\usepackage{mathrsfs}
\setmathfont{Latin Modern Math}
% \usepackage{amssymb} % Contained in package unicode-math
% Jump (Math) \llbracket & \rrbracket
\usepackage{stmaryrd}
% Chemical formulas and equations
\usepackage[version=4]{mhchem}
% Graphics
\usepackage{graphicx}
\graphicspath{ {./images/} }
\usepackage[export]{adjustbox}
% Tables, enumeration
\usepackage{multirow}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{enumitem}
% Adjust the position
\usepackage{float}
% Frames, reference
\usepackage{framed}
\usepackage[strict]{changepage}
\usepackage{hyperref}
\hypersetup{
colorlinks=true,
linkcolor=black,
filecolor=magenta,
urlcolor=blue,
}
% Page & paragraph settings
\usepackage{fancyhdr}
\usepackage{geometry}
\geometry{left=1.5cm, right=1.5cm, top=2cm, bottom=2cm}
\usepackage{indentfirst}
\setlength{\parindent}{2em}
\setlength{\parskip}{0em}
% Algorithm & coding environment
\usepackage[ruled,vlined]{algorithm2e}
\usepackage[framemethod=TikZ]{mdframed}
\usepackage{listings}
\usepackage{wrapfig}
\usepackage{booktabs}
\usepackage{makecell}
% New command
\newcommand\course{COMP 3711}
\newcommand\coursetitle{Design and Analysis of Algorithms}
\newcommand\semester{Fall 2023}
\renewcommand{\labelenumi}{\alph{enumi}}
\newcommand{\Z}{\mathbb Z}
\newcommand{\R}{\mathbb R}
\newcommand{\Q}{\mathbb Q}
\newcommand{\NN}{\mathbb N}
\newcommand{\dd}{\mathrm{d}}
\DeclareMathOperator{\Mod}{Mod}
\renewcommand\lstlistingname{Algorithm}
\renewcommand\lstlistlistingname{Algorithms}
\def\lstlistingautorefname{Alg.}
\newtheorem*{theorem}{Theorem}
\newtheorem*{lemma}{Lemma}
%%%%%%%%%%%%%%% Page Setup %%%%%%%%%%%%%%%
\pagestyle{fancy}
\headheight 35pt
\lhead{\course\ \coursetitle\ \semester}
\rhead{\includegraphics[width=2.5cm]{logo-hkust.png}}
\lfoot{}
\pagenumbering{arabic}
\cfoot{}
\rfoot{\small\thepage}
\headsep 1.2em
%%%%%%%%%%%%%%% Boxframe Setup %%%%%%%%%%%%%%%
\definecolor{blueshade}{rgb}{0.95,0.95,1} % Horizontal Line: DarkBlue
\definecolor{greenshade}{rgb}{0.90,0.99,0.91} % Horizontal Line: Green
\definecolor{redshade}{rgb}{1.00,0.90,0.90}% Horizontal Line: LightCoral
\definecolor{brownshade}{rgb}{0.99,0.97,0.93} % Horizontal Line: BurlyWood
\newenvironment{formal}[2]{%
\def\FrameCommand{%
\hspace{1pt}%
{\color{#1}\vrule width 2pt}%
{\color{#2}\vrule width 4pt}%
\colorbox{#2}%
}%
\MakeFramed{\advance\hsize-\width\FrameRestore}%
\noindent\hspace{-4.55pt}% Disable indenting first paragraph
\begin{adjustwidth}{}{7pt}%
\vspace{2pt}\vspace{2pt}%
}
{%
\vspace{2pt}\end{adjustwidth}\endMakeFramed%
}
%%%%%%%%%%%%%%% Problem Environment Setup %%%%%%%%%%%%%%%
\mdfdefinestyle{problemstyle}{
linecolor=black,linewidth=1pt,
frametitlerule=true,
frametitlebackgroundcolor=gray!20,
roundcorner=10pt,
innertopmargin=\topskip,
frametitlealignment=\hspace{0em},
}
\mdfsetup{skipabove=\topskip,skipbelow=\topskip}
\mdtheorem[style=problemstyle]{Problem}{Problem}
\newenvironment{Solution}{\textbf{Solution.}}
%%%%%%%%%%%%%%% Coding Environment S6etup %%%%%%%%%%%%%%%
\lstset{
basicstyle=\tt,
% Line number
numbers=left,
rulesepcolor=\color{red!20!green!20!blue!20},
escapeinside=``,
xleftmargin=2em,xrightmargin=2em, aboveskip=1em,
% Background frame
framexleftmargin=1.5mm,
frame=shadowbox,
% Background color
backgroundcolor=\color[RGB]{252,236,227},
% Style
keywordstyle=\color{blue}\bfseries,
identifierstyle=\bf,
numberstyle=\color[RGB]{0,192,192},
commentstyle=\it\color[RGB]{0,153,51},
stringstyle=\rmfamily\slshape\color[RGB]{128,0,0},
% Show space
showstringspaces=false
}
%%%%%%%%%%%%%%% Document Begins %%%%%%%%%%%%%%%
\begin{document}
%%%%%%%%%%%%%%% Title Page %%%%%%%%%%%%%%%
\begin{titlepage}
\begin{center}
\vspace*{3cm}
\Huge
\hrulefill
\vspace{1cm}
\huge
\textbf{COMP 3711 Course Notes\\}
\vspace{1cm}
\textbf{Design and Analysis of Algorithms}
\vspace{1cm}
\hrulefill
\vspace{1.5cm}
\Large
\textbf{LIN, Xuanyu}
\vfill
$\mathscr{ALGORITHMS}$
\vspace{1cm}
\course \ Design and Analysis of Algorithms
\vspace{1cm}
\includegraphics[width=0.4\textwidth]{logo-hkust.png}
\\
\Large
\today
\end{center}
\end{titlepage}
%%%%%%%%%%%%%%% Article Begins %%%%%%%%%%%%%%%
\begin{comment}
\begin{abstract}
Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract Abstract
\end{abstract}
\tableofcontents
\begin{center}
\section*{\LARGE Title}
\end{center}
\section{Section 1}
This is a link to \href{https://www.google.com}{Google}.
$$
\vec{\nabla} \cdot \vec{E}=\frac{1}{\epsilon_{0}} \cdot \rho
$$
\begin{formal}{DarkBlue}{blueshade}
\textbf{Theorem 1.1} 这是一段中文。\hyperref[ref1]{[1]}
$$
\vec{\nabla} \cdot \vec{E}=\frac{1}{\epsilon_{0}} \cdot \rho
$$
\noindent This is an English sentence.
\end{formal}
\begin{center}
\begin{tabular}{|c|c|c|}
\hline
\multirow{2}{*}{A} & B & C \\
\cline{2-3}
& D & E \\
\hline
\end{tabular}
\end{center}
\begin{algorithm}
\SetAlgoLined
\KwIn{$a, b$}
\KwOut{$c$}
$c = a + b$\;
\Return{$c$}\;
\caption{Addition}
\end{algorithm}
\begin{Problem}[Title]
\lstset{language=Python}
\begin{lstlisting}[tabsize=4]
print("Hello World!")
\end{lstlisting}
\end{Problem}
\begin{Solution}
Text
\end{Solution}
\section{References}
\label{ref1}
[1] Google \href{https://www.google.com}{https://www.google.com}
\end{comment}
\tableofcontents
\newpage
\section{Asymptotic Notation}
\begin{formal}{DarkBlue}{blueshade}
\noindent \textbf{Upper Bounds} $T(n) = O(f(n))$
if exist constants $c > 0$ and $n_0 \geq 0$ such that for all $n \geq n_0$, $T(n) \leq c \cdot f(n)$.
\noindent \textbf{Lower Bounds} $T(n) = \Omega(f(n))$
if exist constants $c > 0$ and $n_0 \geq 0$ such that for all $n \geq n_0$, $T(n) \geq c \cdot f(n)$.
\noindent \textbf{Tight Bounds} $T(n) = \Theta(f(n))$
if $T(n) = O(f(n))$ and $T(n) = \Omega(f(n))$.
\noindent \textbf{Note:} Here "=" means "is", not equal.
\end{formal}
\section{Introduction - The Sorting Problem}
\subsection{Selection Sort}
\begin{algorithm}
\SetAlgoLined
\KwIn{An array $A[1 ... n]$ of elements}
\KwOut{Array $A[1 ... n]$ of elements in sorted order (asending)}
\For{$i \gets 1$ to $n-1$}{
\For{$j \gets i+1$ to $n$}{
\If{$A[i]>A[j]$}{
swap $A[i]$ and $A[j]$
}
}
}
\caption{Selection Sort}
\end{algorithm}
Running Time: $\frac{n(n-1)}{2}$
Best-Case = Worst-Case: $T(n) = \Theta(\frac{n(n-1)}{2}) = \Theta(n^2)$
\subsection{Insertion Sort}
\begin{algorithm}
\SetAlgoLined
\KwIn{An array $A[1 ... n]$ of elements}
\KwOut{Array $A[1 ... n]$ of elements in sorted order (asending)}
\For{$i \gets 2$ to $n$}{
$j \gets i-1$
\While{$j \geq 1$ and $A[j] > A[j+1]$}{
swap $A[j]$ and $A[j+1]$
}
$j \gets j-1$
}
\caption{Insertion Sort}
\end{algorithm}
Running Time: Depends on the input array, ranges between $(n-1)$ and $\frac{n(n-1)}{2}$
Best-Case: $T(n) = n-1 = \Theta(n)$ (Useless)
Worst-Case: $T(n) = \Theta(\frac{n(n-1)}{2}) = \Theta(n^2)$ (Commonly-Used)
Average-Case: $T(n) = \Theta(\sum_{i=2}^n \frac{i-1}{2}) = \Theta(\frac{n(n-1)}{4}) = \Theta(n^2)$ (Sometimes Used)
\subsection{Wild-Guess Sort}
\begin{algorithm}
\SetAlgoLined
\KwIn{An array $A[1 ... n]$ of elements}
\KwOut{Array $A[1 ... n]$ of elements in sorted order (asending)}
$\pi \gets [4,7,1,3,8,11,5,...]$\ \ Create random permutation
Check if $A[\pi[i]] \leq A[\pi[i+1]]$ for all $i = 1,2,...,n-1$
If yes, output A according to $\pi$ and terminate
else $Insertion-Sort(A)$
\caption{Wild-Guess Sort}
\end{algorithm}
Running Time: Depends on the random generation, could be faster than the insertion sort.
\subsection{Worst-Case Analysis}
The algorithm's worst case running time is $O(f(n)) \implies $ On all inputs of (large) size $n$, the running time of the algorithm is $\leq c \cdot f(n)$.
The algorithm's worst case running time is $\Omega (f(n)) \implies $ There exists at least one input of (large) size $n$ for which the running time of the algorithm is $\geq c \cdot f(n)$.
Thus, Insertion sort runs in $\Theta (n^2)$ time.
\begin{formal}{DarkBlue}{blueshade}
\textbf{Notice}
Selection sort, insertion sort, and wild-guess sort all have worst-case running time $\Theta (n^2)$. How to distinguish between them?
$\bullet$ Closer examination of hidden constants
$\bullet$ Careful analysis of typical expected inputs
$\bullet$ Other factors such as cache efficiency, parallelization are important
$\bullet$ Empirical comparison
\end{formal}
\begin{formal}{DarkGreen}{greenshade}
\textbf{Stirling's Formula}
Prove that $\log (n!) = \Theta (n \log n)$
First $\log (n!) = O (n \log n)$ since:
$$
\log (n!) = \sum_{i=1}^n \log i \leq n \times \log n = O (n \log n)
$$
Second $\log (n!) = \Omega (n \log n)$ since:
$$
\log (n!) = \sum_{i=1}^n \log i \geq \sum_{i=n/2}^n \log i \geq n/2 \times \log n/2 = n/2 (\log n - \log 2) = \Omega (n \log n)
$$
Thus, $\log (n!) = \Theta (n \log n)$
\end{formal}
\newpage
\section{Divide \& Conquer}
\textbf{Main idea of D \& C:} Solve a problem of size $n$ by breaking it into one or more smaller problems of size less than $n$. Solve the smaller problems recursively and combine their solutions, to solve the large problem.
\subsection{Binary Search}
\begin{formal}{Brown}{brownshade}
\textbf{Example: Binary Search}
\textbf{Input:} A sorted array $A[1,...,n]$, and an element $x$
\textbf{Output:} Return the position of $x$, if it is in $A$; otherwise output nil
\textbf{Idea of the binary search:} Set $q \gets$ middle of the array. If $x = A[q]$, return $q$. If $x < A[q]$, search $A[1,...,q-1]$, else search $A[q+1,...,n]$.
\end{formal}
\begin{algorithm}
\SetAlgoLined
\KwIn{Array $A[1 ... n]$ of elements in sorted order}
\SetKwFunction{BinarySearch}{BinarySearch}
\BinarySearch{$A[], p, r, x$}($p, r$ being the left \& right iteration, $x$ being the element being searched){
\If{$p > r$}{
\Return{nil}
}
$q \gets [(p+r)/2]$
\If{$x = A[q]$}{
\Return{$q$}
}
\If{$x < A[q]$}{
\BinarySearch{$A[], p, q-1, x$}
}
\Else{
\BinarySearch{$A[], q+1, r, x$}
}
}
\caption{Binary Search}
\end{algorithm}
Recurrence of the algorithm, supposing $T(n)$ being the number of the comparisons needed for $n$ elements:
\noindent $T(n) = T(\frac{n}{2}) + 2$ if $n > 1$, with $T(1) = 2$.
$\implies T(n) = 2\log_2 n + 2 \implies O(\log n)$ algorithm
\begin{formal}{Brown}{brownshade}
\textbf{Example: Binary Search in Rotated Array}
Suppose you are given a sorted array $A$ of $n$ distinct numbers that
has been rotated $k$ steps, for some unknown integer $k$ between 1 and $n-1$. That is, $A[1 ... k]$ is sorted in increasing order, and $A[k+1 ... n]$ is also sorted in increasing order, and $A[n] < A[1]$.
Design an $O(\log n)$-time algorithm that for any given x,
finds x in the rotated sorted array, or reports that it does not
exist.
\noindent \textbf{Algorithm:}
First conduct a $O(\log n)$ algorithm to find the value of $k$, then search for the target value in either the first part or the second part.
$Find-x(A, x)$
$k \leftarrow Find-k(A, 1, n)$ (First find $k$)
$if\ x \geq A[1]\ then\ return\ BinarySearch(A, 1, k, x)$
$Else\ return\ BinarySearch(A, k+1, n, x)$
\end{formal}
\newpage
\begin{formal}{Brown}{brownshade}
\textbf{Example: Finding the last 0}
You are given an array $A[1 ... n]$ that contains a sequence of 0
followed by a sequence of 1 (e.g., 0001111111). $A$ contains $k$ 0(s) ($k>0$ and $k<<n$) and at least one 1.
Design an $O(\log k)$-time algorithm that finds the position $k$ of the last 0.
\noindent \textbf{Algorithm:}
$i\leftarrow1$
$while\ A[i]=0$
\quad \quad $i\leftarrow2i$
$find-k(A[i/2 ... i])$
\end{formal}
\subsection{Merge Sort}
\textbf{Principle of the Merge Sort:}
$\bullet$ Divide array into two halves.
$\bullet$ Recursively sort each half.
$\bullet$ Merge two halves to make sorted whole.
\begin{algorithm}
\SetAlgoLined
\SetKwFunction{MergeSort}{MergeSort}
\SetKwFunction{Merge}{Merge}
\MergeSort{$A, p, r$}($p, r$ being the left \& right side of the array to be sorted){
\If{$p = r$}{
\Return
}
$q \gets [(p+r)/2]$
\MergeSort{$A, p, q$}
\MergeSort{$A, q+1, r$}
\Merge{$A, p, q, r$}
\underline{First Call:} \MergeSort{$A, 1, n$}
}
\caption{Merge Sort}
\end{algorithm}
\begin{algorithm}
\SetAlgoLined
\KwIn{Two Arrays $L\gets A[p ... q]$ and $R\gets A[q+1 ... r]$ of elements in sorted order}
\SetKwFunction{Merge}{Merge}
\Merge{$A, p, q, r$}{
Append $\infty$ at the end of $L$ and $R$
$i\gets 1,\ j\gets 1$
\For{$k \gets p$ to $r$}{
\If{$L[i] \leq R[j]$}{
$A[k] \gets L[i]$
$i \gets i + 1$
}
\Else{
$A[k] \gets R[j]$
$j \gets j + 1$
}
}
}
\caption{Merge}
\end{algorithm}
Let $T(n)$ be the running time of the algorithm on an array of size $n$.
\noindent \textbf{Merge Sort Recurrence:}
$$
T(n) \leq T(\lfloor n/2 \rfloor) + T(\lceil n/2 \rceil) + O(n), \quad n>1, \quad T(1) = O(1)
$$
\textbf{Simplification:}
$$
\implies T(n) = 2T(n/2) + n, \quad n>1, \quad T(1) = 1
$$
\textbf{Result:}
$$
T(n) = n\log_2 n + n = O(n\log n)
$$
\newpage
\subsection{Inversion Counting}
\textbf{Definition of the Inversion Numbers:} Given array $A[1 ... n]$, two elements $A[i]$ and $A[j]$ are inverted if $i < j$ but $A[i] > A[j]$. The inversion number of $A$ is the number of inverted pairs.
\begin{formal}{DarkBlue}{blueshade}
\textbf{Theorem:}
The number of swaps used by Insertion Sort = Inversion Number (Proved by induction on the size of the array)
\noindent \textbf{Algorithm to Compute Inversion Number:}
Algorithm 1: Check all $\Theta(n^2)$ pairs.
Algorithm 2: Run Insertion Sort and count the number of swaps – Also $\Theta(n^2)$ time.
Algorithm 3: Divide and Conquer
\end{formal}
\subsubsection{Counting Inversions: Divide-and-Conquer}
\textbf{Principle of the Algorithm:}
$\bullet$ Divide: divide array into two halves
$\bullet$ Conquer: recursively count inversions in each half
$\bullet$ Conbine: count inversions where $a_i$ and $a_j$ are in different halves, and return sum of three quantities
Inversion counting during the combine step is very similar to the Merge Algorithm (Algorithm 6), by counting the sum of each inversion number of the right array (indicated by $I[j]$) comparing to the left array.
\begin{algorithm}
\SetAlgoLined
\KwIn{Two Arrays $L\gets A[p ... q]$ and $R\gets A[q+1 ... r]$ of elements in sorted order}
\SetKwFunction{Count}{Count}
\Count{$A, p, q, r$}{
$i\gets 1,\ j\gets 1,\ c\gets 0$
\While{$(i \leq q-p+1) \&\& (j \leq r-q)$}{
\If{$L[i] \leq R[j]$}{
$i \gets i+1$
}
\Else{
$I[j] = q-p-i+2$
$c \gets c+I[j]$
$j \gets j+1$
}
}
}
\caption{Inversion Count during Combination}
\end{algorithm}
The time-complexity of the algorithm is $\Theta(n\log n)$, same as the Merge Sort.
\subsubsection{Implementation of the Algorithm}
\begin{algorithm}
\SetAlgoLined
\SetKwFunction{Sort}{Sort-and-Count}
\SetKwFunction{Merge}{Merge-and-Count}
\Sort{$A, p, r$}{
\If{$p = r$}{
\Return{0}
}
$q \gets \lfloor(p+r)/2\rfloor$
$c_1 \gets$ \Sort{$A, p, q$}
$c_2 \gets$ \Sort{$A, q+1, r$}
$c_3 \gets$ \Merge{$A, p, q, r$}
\Return{$c_1 + c_2 + c_3$}
\underline{First Call:} \Sort{$A, 1, n$}
}
\caption{Main Algorithm}
\end{algorithm}
\begin{algorithm}
\SetAlgoLined
\KwIn{Two Arrays $L\gets A[p ... q]$ and $R\gets A[q+1 ... r]$ of elements in sorted order}
\SetKwFunction{Merge}{Merge-and-Count}
\Merge{$A, p, q, r$}{
Append $\infty$ at the end of $L$ and $R$
$i\gets 1,\ j\gets 1, c\gets 0$
\For{$k \gets p$ to $r$}{
\If{$L[i] \leq R[j]$}{
$A[k] \gets L[i]$
$i \gets i + 1$
}
\Else{
$A[k] \gets R[j]$
$j \gets j + 1$
$c \gets c+q-p-i+2$
}
}
\Return{$c$}
}
\caption{Merge-and-Count}
\end{algorithm}
\subsection{Basic Summary of D\&C: Problem Size \& Number of Problems}
\textbf{Observations of D\&C in Logarithmic Patterns:}
$\bullet$ Break up problem of size $n$ into $p$ parts of size $n/q$.
$\bullet$ Solve parts recursively and combine solutions into overall solution.
$\bullet$ At level $i$, we break $i$ times and we have $p^i$ problems of size $n/q^i$.
$\bullet$ When we cannot break up any more, usually when the problem size
becomes 1. Usually $i \approx \log_q n$.
\begin{formal}{DarkGreen}{greenshade}
The number of problems at (bottom) level $\log_q n$ is $p^i = p^{\log_q n} = n^{\log_q p}$.
\end{formal}
\vspace{1em}
\textbf{Observations of D\&C in Non-Logarithmic Patterns:}
$\bullet$ Break up problem of size $n$ into $p(\leq 2)$ parts of size $n-q$. (e.g. $q=1$ for Hanoi Problem)
$\bullet$ Assume that $q=1$
$\bullet$ At level i, we break $i$ times and we have $p^i$ problems of size $n-i$.
$\bullet$ If we stop when the problem size becomes 1, then $n-i=1 \implies i=n-1$.
\begin{formal}{DarkGreen}{greenshade}
The number of problems at (bottom) level $n-1$ is: $p^i = p^{n-1}$.
\end{formal}
\subsection{Maximum Contiguous Subarray}
\begin{formal}{Brown}{brownshade}
\textbf{Example: The Maximum Subarray Problem}
\textbf{Input:} An array of numbers $A[1,...,n]$, both positive and negative
\textbf{Output:} Find the maximum $V(i, j)$, where $V(i, j) = \sum_{k=i}^j A[k]$
\noindent \textbf{Brute-Force Algorithm}
\textbf{Idea:} Calculate the value of $V(i, j)$ for each pair $i\leq j$ and return the maximum value.
Requires three nested for-loop, time complexity: $\Theta(n^3)$.
\noindent \textbf{A Data-Reuse Algorithm}
\textbf{Idea:} $V(i, j) = V(i, j-1) + A[j]$
Requires two nested for-loop, time complexity: $\Theta(n^2)$.
\end{formal}
\newpage
\subsubsection{A D\&C Algorithm}
\textbf{Idea:} Cut the array into two halves, all subarrays can be classified into three cases: entirely in the first/second half, or crosses the cut.
\textbf{Compare with the merge sort:} Whole algorithm will run in $\Theta(n\log n)$ time if the cross-cut can be solved in $O(n)$ time.
\begin{algorithm}
\SetAlgoLined
\SetKwFunction{MaxSubArray}{MaxSubArray}
\MaxSubArray{$A, p, r$}{
\If{$p = r$}{
\Return{$A[p]$}
}
$q \gets \lfloor(p+r)/2\rfloor$
$M_1 \gets$ \MaxSubArray{$A, p, q$}
$M_2 \gets$ \MaxSubArray{$A, q+1, r$}
$L_m, R_m \gets -\infty$
$V \gets 0$
\For{$i \gets q$ to $p$}{
$V \gets V+A[i]$
\If{$V>L_m$}{
$L_m \gets V$
}
}
$V \gets 0$
\For{$i \gets q+1$ to $r$}{
$V \gets V+A[i]$
\If{$V>R_m$}{
$R_m \gets V$
}
}
\Return{$\max(M_1, M_2, L_m+R_m)$}
\underline{First Call:} \MaxSubArray{$A, 1, n$}
}
\caption{Maximum Subarray}
\end{algorithm}
\textbf{Recurrence:} $T(n) = 2T(n/2)+n \implies T(n) = \Theta(n\log n)$
\subsubsection{Kadane's Algorithm}
\textbf{Idea:} Based on the principles of \textbf{Dynamic Programming}. Let $V[i]$ be the (local) maximum sub-array that ends at $A[i]$, then we let:
$\bullet V[1] = A[1]$
$\bullet V[i] = \max(A[i], A[i] + V[i-1])$
The maximum of $V[i]$, namely $V_{max}$ is the maximum continuous subarray found so far.
\begin{algorithm}
\SetAlgoLined
$V_{max} \gets -\infty; V \gets 0; \text{start} \gets 1; \text{end} \gets 1; \text{temp} \gets 1$ (Note: start \& end specify the maximum sub-array)
\For{$i\gets 1$ to $n$}{
$V\gets V+A[i]$
\If(// Implies $V[i-1]$ is negative, restart from the current position){$V < A[i]$}{
$V\gets A[i]; \text{temp}\gets i$
}
\If(// Found a max sum, update start and end){$V > V+{max}$}{
$V_{max}\gets V; \text{start}\gets \text{temp}; \text{end}\gets i$
}
}
\caption{Kadane's Algorithm}
\end{algorithm}
\textbf{Time Complexity:} $\Theta(n)$
\begin{formal}{Brown}{brownshade}
\textbf{Example: Maximizing Stock Profits}
You are presented with an array $p[1\dots n]$ where $p[i]$ is the price of the stock on day $i$.
Design an divide-and-conquer algorithm that finds a strategy to make as much money as possible, i.e., it finds a pair $i, j$ with $1\leq i\leq j\leq n$ such that $p[j]-p[i]$ is maximized over all possible such pairs. Note that you are only allowed to buy the stock once and then sell it later.
\vspace*{1em}
\noindent \textbf{Idea 1: Divide and Conquer}
$\bullet$ Cut the array into two halves.
$\bullet$ All $i, j$ solutions can be classified into three cases: both $i, j$ are entirely in the first(second) half, or $i$ is in the left half while $j$ is in the right half.
$\bullet$ Maximizing a Case 3 result $p[j]-p[i]$ means finding the smallest value in the first half and the largest in the second half.
\textbf{Time Complexity:} $T(n) = 2T(n/2) + n \implies T(n) = \Theta(n\log n)$
\vspace*{1em}
\noindent \textbf{Idea 2: Kadane's Algorithm}
$\bullet$ Create a \textbf{Profit} array with $Profit[i]=Price[i+1]-Price[i]$.
$\bullet$ Perform the Kadane's Algorithm.
\textbf{Time Complexity:} $O(n)$
\end{formal}
\subsection{Integer Multiplication}
\subsubsection{A Simple D\&C Algorithm for Integer Multiplication}
\textbf{Goal:} Given two $n$-bit binary integers $a$ and $b$, compute: $a\cdot b$.
\textbf{Idea:} Multiplication by $2^k$ can be done in one time unit by a left shift of $k$ bits.
$\bullet$ Rewrite the two numbers as $a = 2^{n/2} a_1 + a_0$, $b = 2^{n/2} b_1 + b_0$.
$\bullet$ The product becomes: $a\cdot b = (2^{n/2} a_1 + a_0)(2^{n/2} b_1 + b_0) = 2^n a_1 b_1 + 2^{n/2} (a_1 b_0 + a_0 b_1) + a_0 b_0$
$\bullet$ The new computation requires 4 products of integers, each with $n/2$ bits.
$\bullet$ Apply D\&C by splitting a problem of size $n$, to 4 problems of size $n/2$.
\begin{algorithm}
\SetAlgoLined
\SetKwFunction{Multiply}{Multiply}
\Multiply{$A, B$}{
$n\gets$ size of $A$
\If{$n = 1$}{\Return{$A[1]\cdot B[1]$}}
$mid \gets \lfloor n/2 \rfloor$
$U \gets$ \Multiply($A[mid+1..n], B[mid+1..n]$) // $a_1b_1$
$V \gets$ \Multiply($A[mid+1..n], B[1..mid]$) // $a_1b_0$
$W \gets$ \Multiply($A[1..mid], B[mid+1..n]$) // $a_0b_1$
$Z \gets$ \Multiply($A[1..mid], B[1..mid]$) // $a_0b_0$
$M[1..2n]\gets 0$
$M[1..n]\gets Z$ // $a_0b_0$
$M[mid+1..]\gets M[mid+1..] \oplus V \oplus W$ // $+[(a_1b_0+a_0b_1)\ll\text{(left shift) } n/2]$
$M[2mid+1..]\gets M[2mid+1..] \oplus U$ // $+[a_1b_1\ll n]$
\Return{$M$}
}
\caption{Binary Multiplication}
\end{algorithm}
\textbf{Time Complexity:} $T(n) = 4T(n/2) + n\implies T(n) = \Theta(n^2)$
\newpage
\subsubsection{Karatsuba Multiplication}
\textbf{Goal:} Given two $n$-bit binary integers $a$ and $b$, compute: $a\cdot b$.
\textbf{Idea:}
$\bullet$ We've seen that $ab = a_1b_1 2^n + (a_1b_0+a_0b_1) 2^{n/2} + a_0b_0$, so we only need the result of $a_1b_0+a_0b_1$.
$\bullet$ Note that $a_1b_0+a_0b_1 = (a_1+a_0)(b_1+b_0) - a_1b_1 - a_0b_0$, thus only requires performing 3 multiplications of size $n/2$.
\begin{algorithm}
\SetAlgoLined
\SetKwFunction{Multiply}{Multiply}
\Multiply{$A, B$}{
$n\gets$ size of $A$
\If{$n = 1$}{\Return{$A[1]\cdot B[1]$}}
$mid \gets \lfloor n/2 \rfloor$
$U \gets$ \Multiply($A[mid+1..n], B[mid+1..n]$) // $a_1b_1$
$Z \gets$ \Multiply($A[1..mid], B[1..mid]$) // $a_0b_0$
$A'\gets A[mid+1..n] \oplus A[1..mid]$ // $a_1+a_0$