-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_structures.tex
More file actions
11028 lines (10270 loc) · 434 KB
/
Copy pathdata_structures.tex
File metadata and controls
11028 lines (10270 loc) · 434 KB
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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% name: data_structures.tex
% author: Leo Liberti
% purpose: book for INF421
% history: 120604 - work started (over the Atlantic, south of
% Iceland)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass[a4paper]{book}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb} %additional math symbols
\usepackage{amsopn}
\usepackage{theorem} %additional LaTeX2e package
\usepackage{latexsym}
\usepackage{mathrsfs} %calligraphic fonts
\usepackage{tikz}
\usepackage{pgfplots}
%\usepackage{tkz-arith}
\usepackage{tikz-qtree}
\usepackage{tkz-graph}
%\usepackage{tkz-berge}
\usepackage{url}
\usepackage{verbatim}
\usepackage{algorithm}
\usepackage{algorithmic}
\usepackage[Lenny]{fncychap}
\usepackage{graphicx} %graphic and .eps files
\usepackage{psfrag}
\usepackage{hyperref}
\input{../../../templates/definecolors.tex}
\setlength{\parindent}{0.5cm}
\setlength{\parskip}{0.3cm}
% the following settings leave nearly no margins. For defaults, rem out.
\setlength{\oddsidemargin}{0.5cm}
% rem out following for one-side only
\setlength{\evensidemargin}{-0.58cm}
%%
\setlength{\textwidth}{16cm}
\setlength{\textheight}{23cm}
\setlength{\footskip}{1cm}
\setlength{\topmargin}{0cm}
%% ______________________etc_____________________________
\makeindex
\pagestyle{headings}
\renewcommand{\baselinestretch}{1}
% N.B. if paper has sections and subsections add "[section]"
% or "[subsection]" at the end of the following 5 lines.
\newtheorem{result}{\ }[section]
\theoremstyle{changebreak} % (see LATEX2E\THEOREM.DTX)
\newtheorem{thm}[result]{Theorem}
\newtheorem{defn}[result]{Definition}
\newtheorem{lem}[result]{Lemma}
\newtheorem{cor}[result]{Corollary}
\newtheorem{prop}[result]{Proposition}
\newtheorem{eg}[result]{Example}
\newtheorem{ex}[result]{Exercise}
\newenvironment{proof}
{{\sl Proof.}\hspace*{1 ex}}%
{{\nopagebreak\hspace*{\fill}$\Box$\par\vspace{12pt}}}
%
\renewcommand{\vec}[1]{\underline{#1}}
\newcommand{\transpose}[1]{{#1}^{\top}}
\DeclareMathOperator{\dom}{\mathrm{dom}}
\DeclareMathOperator{\inc}{\mathrm{inc}}
%
\setcounter{secnumdepth}{6}
\setcounter{tocdepth}{4}
\begin{document}
\thispagestyle{empty}
\begin{center}
{\LARGE INF421: Data Structures and algorithms} \\ [4cm]
{\sc \Large Leo Liberti} \\ [1cm]
{\it LIX, Ecole Polytechnique, 91128 Palaiseau, France} \\ [1cm]
\url{liberti@lix.polytechnique.fr} \\ [4cm]
\today
\end{center}
\newpage
\thispagestyle{empty}
\vspace*{5cm}
\begin{flushright}
{\it To\footnote{Not a spelling mistake.} Much}
\end{flushright}
\newpage
\thispagestyle{empty}
Chers \'el\`eves,
vous avez entre vos mains la premi\`ere version de mon polycopi\'e
pour le cours INF421 ({\it Les bases de l'algorithmique et de la
programmation}) de l'Ecole Polytechnique. En tant que premi\`ere
version, ce polycopi\'e contiendra sans doute beaucoup d'erreurs:
merci de m'envoyer un email \`a \url{leoliberti@gmail.com} pour m'en
faire part, si vous en trouvez.
Je vous rappelle que le website du cours INF421
\begin{center}
\url{www.enseignement.polytechnique.fr/informatique/INF421/}
\end{center}
contient beaucoup de mat\'eriel didactique. Le blog
\begin{center}
\url{inf421.wordpress.com}
\end{center}
contient du mat\'eriel didactique suppl\'ementaire quand le cours est
actif. Pour le reste de l'ann\'ee, j'y publie n'importe quoi.
%% L'ann\'ee derni\`ere, j'ai re\c{c}u des critiques de la part des
%% \'el\`eves principalement sur trois points: (i) la disconnexion entre
%% ce qui \'etait enseign\'e en amphi et les exercices des TDs; (ii)
%% l'absence du code dans les {\it slides} present\'es pendant le cours;
%% (iii) l'absence du polycopi\'e. Evidemment, ce texte est une r\'eponse
%% au point (iii). Pour ce qui concerne le point (ii), ce polycopi\'e
%% contient beaucoup de code dans les premiers chapitres, qui
%% dispara\^{\i}t au fur et \`a mesure que le discours passe du codage
%% \`a l'abstraction du m\^eme (l'algorithme), jusqu'\`a en avoir presque
%% plus dans les derniers chapitres. En tout cas, on n'apprend pas a
%% coder en lisant du code: il faut le cr\'eer avec son propre cervau,
%% et le b\^atir avec ses propres mains.
%% Pour ce qui concerne le point (i), voici mon opinion. Assister \`a une
%% s\'eance d'amphi qui introduise exactement ce qui sera vu dans le TD,
%% sert a un seul but: minimiser le travail de l'\'el\`eve, en maximisant
%% ses r\'esultats. Je comprends donc bien les critiques en ce sens, mais
%% les \'el\`eves sont partie en cause: c'est {\it evident} que vous
%% vouliez le maximum des r\'esultats avec le minimum de
%% l'effort. Malheureusement, cet approche minimise aussi le
%% d\'eveloppement de l'intelligence. Il produirait un cours le plus
%% modulaire possible, avec chaque argument, reduit \`a ses termes
%% minimales, pr\^et \`a \^etre m\'emoris\'e ou compris avec le moins
%% possible de fatigue mentale, et pas d'autres notions enseign\'ees sauf
%% celles qui seraient directement utiles pour l'exercice du TD. Sachez
%% donc que {\it intelligence} et un mot qui vient du latin {\it
%% interligo}, un m\'elange de ``entre'' ({\it inter}) et ``associer''
%% ({\it ligare}). L'intelligence, \`a la base, c'est faire des liens
%% entre des conceptes diff\'erentes. L'acteur intelligent, si ce
%% n'\'etait pas encore clair, c'est la personne qui {\it \'etablit} les
%% liens. Si l'enseignant vous donne tous les liens, ou, pire, vous les
%% coupes pour ``modulariser'' les arguments, emp\`eche le
%% d\'eveloppement de votre intelligence. Aucun enseignant ferait \c{c}a
%% expr\`es: il lui serait moralement interdit. Sans compter que le but
%% de ce cours d'informatique n'est pas du tout celui de ``faire bien les
%% exercices en TD'': les exercices sont un {\it moyen}, pas un {\it
%% fin}.
%% Comme c'est un enseignant (moi) qui a \'ecrit ce polycopi\'e, et pas
%% un \'el\`eve, il va de soi que c'est {\it mes} souhaits qu'il
%% refl\`ete, et pas le v\^otres. Ce texte vous propose bien plus
%% d'arguments du minimum essentiel, ne vous encapsule pas trop les
%% savoirs, et fait tr\`es peu d'efforts pour vous faciliter la vie en
%% TD. Il y a \'evidemment des forts liens conceptuels entre polycopi\'e,
%% amphis, et TDs; mais il y a des notions dans le cours qui ne sont
%% mentionn\'ees qu'en TD, qu'en amphi, que dans ce polycopi\'e. C'est
%% cens\'e am\'eliorer l'esprit d'ind\'ependence de l'\'el\`eve, ainsi
%% que sa cr\'eativit\'e. En somme, ce texte, mes amphis, les TDs, et
%% l'entiert\'e de mon travail d'enseignant, vont dans la direction de
%% vous contraindre a {\it faire des efforts pour comprendre}. Votre
%% affiliation prestigieuse d\'eclare \`a la France enti\`ere que vous
%% \^etes les ingenieurs les plus intelligents et plus capables: pensez a
%% devenir plus intelligents, et laissez tomber la minimisation des
%% efforts.
%% Par ailleurs, je vous invite a m'envoyer des emails, m\^eme beaucoup
%% d'emails, si vous avez des questions, pr\'ecises ou non, sur le
%% contenu du cours: d\'evelopper l'intelligence se fait par lecture, par
%% \'ecoute, par apprentissage pratique, mais encore plus par
%% discussion. Un livre peut vous dire ce qui est, mais les questions les
%% plus ardues concernent ce qui n'est pas: quand vous trouvez une
%% incoh\'erence entre ce que vous avez compris et ce que vous lisez
%% quelque part, aucun livre peut vous r\'epondre, car ce doute ne
%% concerne que vous. C'est bien dans des cas pareils que vous devez
%% demander l'aide de vos enseignants. Jusqu'\`a ce que je resterai votre
%% enseignant, je vous promets de faire de mon mieux pour vous repondre,
%% sinon dans la foul\'ee, dans journ\'ee; ou, au pire, dans la semaine.
\begin{flushright}
{\sc Leo Liberti}, Paris, Ao\^ut 2012
\end{flushright}
\tableofcontents
\nocite{mehlhorn,baptiste_inf421,dowek,knuthNew1}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%% PART I %%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\part{Preliminaries and reminders}
%%%%%%%%%%%%%%%%% CHAPTER: INTRODUCTION %%%%%%%%%%%%%%%%%%%%
\chapter{Computation}
\label{c:computation}
\begin{center}
\fbox{\begin{minipage}{13cm}{\small {\sc Abstract}. What
is a computer and how we represent it formally: what can be
computed and what cannot. Programming languages: what can be
expressed and what cannot. Touching on Java. Efficient
computation: problems, data structures, and
algorithms. Worst-case complexity.}
\end{minipage}}
\end{center}
This introductory chapter briefly touches on some deep theoretical
topics, most of which are presented in the INF423 course, as well as
in many textbooks (e.g.~\cite{minsky}).
\section{Computer hardware}
\label{s:computation:practice}
A computer is a piece of machinery engineered for carrying out
computations electronically. Most computers consist of a {\it Central
Processing Unit} (CPU),\index{CPU} some banks of {\it Random-Access
Memory} (RAM)\index{RAM}, several {\it Input/Output} (IO)\index{IO}
devices, that allow the communication with the user and the external
world, as well as a motherboard that wires all the components
together. At any given instant, the CPU has a {\it state}\index{state}
$s$ out of a possible set $S$ of states. With a given frequency $f$,
the CPU reads and executes a new {\it instruction},\index{instruction}
supplied by the user, which changes its state. According to the state
it is in, the CPU may perform arithmetic or logical operations on
data, read data from or write it to RAM, send data to or receive it
from IO devices.
\subsection{Programs}
\label{s:computation:programs}
Instructions are normally supplied by the user as an ordered list,
also called a {\it program}.\index{program} The ``default behaviour''
of the CPU is to execute instructions in the user-provided sequence,
unless the instruction itself explicitly tells the CPU to jump to a
given point in the sequence. There are instructions that tell the CPU
to test a given logical condition and act differently according to the
results of the test.
We remark that, since a program is defined as an ordered list of
instructions, and any sublist of a list is also a list, any
``subprogram'' is also a program, i.e.~we might use the same term
``program'' to refer to certain subsets of instructions of a given
program.
\section{Computer model}
\label{s:computation:theory}
The computer, as described in Sect.~\ref{s:computation:practice}, was
first conceived by Alan Turing\index{Turing, A.} in 1936 \cite{turing}.
Turing's mathematical model of the computer is called {\it Turing
Machine} (TM).\index{Turing!machine} A TM\index{TM} consists of an
infinite tape,\index{tape} divided into a countably infinite number of
cells,\index{cell} with a device (called {\it head})\index{head} that
can read or write symbols\index{symbol} out of a given alphabet
$A$\index{alphabet} on each cell of the tape. According to the state
$s\in S$ the TM is in, the head either reads, or writes, or moves its
position along the tape. Any TM has a set of instructions that tell it
how to change its state. Turing showed that there exist TMs which can
simulate the behaviour of any other TM: such TMs are called {\it
Universal Turing
Machines}\index{Turing!machine!universal}
\index{universal!Turing machine} (UTM).\index{UTM}
Turing's work spawned further research, from the 1950s onwards, aimed
at simplifying the description of UTMs, involving scientists of
the caliber of Shannon\index{Shannon} \cite{shannonUTM} and
Minsky\index{Minsky} \cite{minskyUTM}. More recently,
Rogozhin\index{Roghozin} \cite{roghozin} described UTMs with low
values of $(|S|,|A|)$, e.g. $(24,2)$, $(10,3)$, $(7,4)$, $(5,5)$,
$(4,6)$, $(3,10)$, $(2,18)$. It appears clear that there is a
trade-off\index{trade-off} between number of states and number of
symbols in the alphabet.
\subsection{Models of computation}
\label{s:computation:models}
UTMs are not the only existing models of computation\index{model of
computation} --- several others exist, sometimes very different from
each other (see e.g.~the {\it Game of Life},\index{Game of Life} a
model for bacteria diffusion \cite{gameoflife}). Such models are said
to be Turing-complete\index{Turing-complete} if they can
simulate\index{simulation} a UTM. ``Simulating'', in this context,
means using a different model $C$ of computation in order to mimick
the behaviour of a UTM. To prove this, it suffices to show that every
instruction, state and symbol of the UTM can be simulated by $C$. If
the UTM can also simulate $C$, then $C$ is said to be
Turing-equivalent.\index{Turing-equivalent}
\subsection{Church's Thesis}
\label{s:computation:churchthesis}
{\it Church's Thesis}\index{Church, A.}\index{Church's thesis}
is the statement that every Turing-complete model of computation is
also Turing-equivalent. So far, no Turing-complete model of
computation was found to be more ``powerful'' than the UTM.
\section{Languages}
\label{s:computation:languages}
A {\it programming language}\index{language}\index{programming
language} is a set of rules for formulating instructions of a
computer program.\index{program} A language, by itself, does not
compute. Programs written in a given language do not compute
either. The relevant model of computation is a computer running a
program written in a given language. It makes sense, however, to
question the ``expression power'' of a language, e.g.~is it
sufficiently expressive that it can write a program that, executed on
a computer, simulates a UTM? If so, then the language is called {\it
universal}.\index{universal!language} It was shown in
\cite{universallang} that, in order to be universal, a given language
should be able to express concatenation, tests and loops.
The {\it concatenation}\index{concatenation} of two instructions $I_1$
and $I_2$ is the program $I_1; I_2$. By induction, the concatenation
of two programs $P_1$ and $P_2$ is the program $P_1; P_2$. A {\it
test}\index{test} instruction modifies the sequence of the
instructions in a program according to whether a given logical
condition is true or false. A {\it loop}\index{loop} is an instruction
that tells the CPU to repeat the execution of a given program.
It is important to keep in mind the distinction between the language
and its underlying computing model. A computing model with no
provision for simulating a memory\index{memory} device (be it a
tape\index{tape} or RAM\index{RAM} or otherwise), may very well
execute a program written in a universal language, but the resulting
computing model will fail to be
Turing-complete.\index{Turing-complete}
\subsection{Declarative languages}
\label{s:computation:declarative}
So far, we made the assumption that programs consist of instructions
that tell a computer (be it hardware or theoretical) to act in certain
ways. The class of languages for expressing such programs are called
{\it imperative
languages}.\index{language!imperative}\index{imperative} There is
another class of programming languages, called {\it declarative
languages},\index{language!declarative}\index{declarative} which are
designed to describe sets (e.g., the set of even numbers can be
described as $\{n\in\mathbb{N}\;|\;n\bmod 2 = 0\}$). Java,\index{Java}
C,\index{C} C++,\index{C++} Basic,\index{Basic}
Fortran,\index{Fortran} Pascal\index{Pascal} are all imperative
languages.
Insofar as a computer acts on input data to produce output data, it
can be seen as a function. Since the formal definition of a
function\index{function} $f$ is a set $F$ of pairs $(\iota,\omega)$
such that $f(\iota)=\omega$, we can describe a function by means of
the set $F$. In this sense, in order to fully describe $f$, it would
suffice to list a set of mathematical conditions that hold for any set
$V$ if and only if $V=F$. Declarative\index{declarative} programming
languages allow such descriptions. Prolog,\index{Prolog}
LISP,\index{LISP} CAML,\index{CAML} AMPL\index{AMPL} are all
declarative languages (most also integrate some imperative
instructions, too). An interesting example of a declarative universal
language\index{language!universal} is given by Diophantine
equations,\index{Diophantine equation}
i.e.~polynomial\index{polynomial} equations with integer coefficients,
where the solutions are constrained to be integers \cite{jones}: the
solution set of certain Diophantine equations define functions that
turn out to describe the input/output pairs of a UTM.\index{UTM}
\subsection{Decidability}
\label{s:computation:decidability}
Functions $\mathbb{N}\to\mathbb{N}$ represented by TMs are called {\it
computable}.\index{function!computable}\index{computable} Sets
$V\subseteq\mathbb{N}$ that are domains\index{domain} (or
co-domains)\index{co-domain} of computable functions are called {\it
recursively enumerable}\index{recursively enumerable}. If $V$ and
$\mathbb{N}\smallsetminus V$ are both recursively enumerable, then
they are both also called {\it
recursive}\index{set!recursive}\index{recursive} or {\it
decidable}\index{set!decidable}\index{decidable}. Given a set
$V\subseteq\mathbb{N}$ and an integer $v\in\mathbb{N}$, one may ask
whether $v\in V$ or not. This is a fundamental decision
problem\index{problem!decision}\index{decision} in number theory. It
turns out that $V$ is recursively enumerable if and only if there is a
program that answers YES when $v\in V$, but may answer wrongly or even
fail to terminate when $v\not\in V$; moreover, $V$ is decidable if and
only if there is a program that answers YES when $v\in V$ and NO when
$v\not\in V$. This provides a further link between imperative and
declarative languages.
It should appear clear that recursively enumerable sets are of limited
value as far as proving that an answer to a problem is correct: if the
algorithm answers YES, it may be a true positive or a false negative,
and there is no way to tell. Moreover, how is a user supposed to know
whether a program fails to terminate\index{termination!failure} or is
simply taking a long time? Accordingly, we try to frame problems so
that the solution set is decidable.\index{decidable}
On the other hand, several interesting sets fail to be decidable.
Take, for example, Hilbert's\index{Hilbert, D.} tenth problem: {\it
determine whether or not there exists a mechanical procedure for
solving a given Diophantine equation}.\index{Diophantine equation}
Given the extent of work on Diophantine equations carried out ever
since Greek civilization, this is certainly an interesting problem.
It remained open until Matyasevi\v{c}\index{Matyasevi\v{c}} answered
in the negative \cite{jones}, by proving that there are parametric
Diophantine equations whose solution set spans the totality of
recursively enumerable\index{recursively enumerable} sets. Since
decidable\index{decidable} sets are a proper subset of recursively
enumerable sets, there clearly are Diophantine equations whose
solution set is undecidable.\index{undecidable}
\subsection{Java}
\label{s:computation:java}
Our programming language of choice is Java\footnote{Its basic syntax
was provided in previous courses, such as INF311 and
INF321.}.\index{Java} In Java, one can:
\begin{itemize}
\item initialize a variable:\index{variable}
\begin{verbatim}
int i;
\end{verbatim}
\item assign a constant value to a variable:\index{constant}
\begin{verbatim}
i = 3;
\end{verbatim}
\item define a function:\index{function}
\begin{verbatim}
int f(int s) {
s = 1;
return s;
}
\end{verbatim}
e.g.~the above defines the trivial function $f:\mathbb{N}\to\{1\}$
that maps every integer to 1
\item test a condition:\index{test}
\begin{verbatim}
if (i < 3) {
f(i);
} else {
i = 0;
}
\end{verbatim}
\item loop indefinitely over a program:\index{loop}
\begin{verbatim}
while(true) {
f(i);
}
\end{verbatim}
\end{itemize}
The fundamental constructs above can be mixed in a number of
syntactically correct ways in order to produce increasingly complex
programs.
\section{Efficiency}
\label{s:computation:efficiency}
Although the questions ``what can you compute with a given computer?''
and ``what can you write with a given language?'' are certainly the
most fundamental --- and universality\index{universal} gives a
theoretical measure of how far computers and languages can provide an
answer to these questions --- there remains the important question of
efficiency.\index{efficient} How efficiently can a language express a
certain program, and how fast can a computer execute a given program?
The answers to these questions largely define the science (and art) of
algorithmics.
\subsection{Structuring data}
\label{s:computation:datastructures}
In the vast majority of real computers, RAM\index{RAM} is organized as
a long but finite list of {\it Binary digITs} (bits).\index{bit} In
the jargon of TMs, the underlying alphabet\index{alphabet} is
$\{0,1\}$, and each cell of the tape can hold either
symbol.\index{symbol} Although this is sufficient to guarantee
universality, it is cumbersome for people to program using only two
symbols.
Accordingly, a {\it data structure}\index{data!structure} is a
segmentation of memory\index{memory} that carries a certain meaning to
the user. For example, people noticed that most integers arising in
practice are in the range $\mbox{\tt
int}=\{-2^{31},\ldots,2^{31}-1\}$.\index{int@{\tt int}} Integers in this
range can be described by sequences of exactly 32 bits (i.e.~4
bytes\footnote{One byte contains 8 bits.}: 31 bits are used to store
the absolute value, and the remaining bit is used for the sign). In TM
jargon, this is akin to taking 32 binary cells on the tape\index{tape}
and declaring them to simply be ``one cell'' which can hold any
integer in the range {\tt int}. This, by the way, also provides a
very simple example of simulation\index{simulation} of a TM with
$|A|=32$ by a TM with $|A|=2$.
In real computers, we are not bound to segmenting memory using only
one data structure:\index{data!structure} a part of memory can hold
{\tt int}s, another can hold bits, and yet another can hold {\tt
double}s\index{double@{\tt double}} (a data structure for storing a certain
subset of rational numbers). Moreover, most programming languages
allow users to declare their own data structures by combining the
elementary\index{data!structure!elementary} ones in different ways. In
order to make it even easier to write programs with user-defined data
structures,\index{data!structure!user-defined}
languages\label{language} usually also allow for pairing such
structures with dedicated user-defined
functions\index{function!user-defined} that handle them appropriately.
In Java, user-defined data structures are called {\it
objects};\index{object} the formal description of an object in terms
of elementary data structures is a {\it class}.\index{class} The data
items occurring in classes are called {\it
attributes},\index{attribute} and the functions items are called
{\it methods}.\index{method}
\subsection{Problems}
\label{s:computation:problem}
It should be clear that programs take data as input, manipulate these
data, and produce data as output. Not all possible data are valid for
input (think of a program that takes a 16-bit integer as input and is
fed a 32-bit one instead --- something like this made the Ariane 5
rocket explode!), and the set of output data is well-defined. A
program $P$ therefore defines a set ${\cal I}$ of possible inputs and
a set ${\cal O}$ of possible outputs. Do ${\cal I},{\cal O}$ uniquely
define the program that produced them? The answer is no: take for
example ${\cal I}={\cal O}=\{n\in\mbox{\tt int}\;|\;n\bmod 2=0\land
n\in[0,10]\}$. This can be obtained with either of the following
(different) programs:
\begin{verbatim}
/* code 1 */
int i = 0;
while(i < 10) {
i += 2;
System.out.println(i);
}
/* code 2 */
int i = 0;
while(i < 10) {
if (i % 2 == 0) then
System.out.println(j);
}
i++;
}
\end{verbatim}
We formally define a {\it problem}\index{problem} to be a set of pairs
$(\iota,\omega)$. A problem is {\it
decidable}\index{problem!decidable}\index{decidable} if there is at
least a program (or TM) $P$ with input set ${\cal I}$ and output set
${\cal O}$ such that $\omega=P(\iota)$ for all $(\iota,\omega)\in
{\cal I}\times {\cal O}$. A decidable problem can also be seen as the class
of all programs that produce the same output $\omega\in {\cal O}$ on a
given input $\iota\in {\cal I}$, and reject all input not in ${\cal
I}$.
\subsection{Algorithms}
\label{s:computation:algorithm}
Loosely speaking, we use ``algorithm'' and ``program''
interchangeably; a ``program'' usually indicates actual code that can
be compiled and executed by a computer, whereas an ``algorithm'' is an
idealized model of a program. An algorithm might contain a statements
in natural (rather than formal, see Sect.~\ref{s:tree:language})
language, or be written formally but for a machine that does not exist
in practice. In general, ``algorithm'' has a theoretical connotation,
whereas ``program'' has a practical one. More formally, an {\it
algorithm}\index{algorithm} is any program solving a decidable
problem.\index{problem!decidable}
\subsubsection{Algorithmic complexity}
\label{s:computation:complexity}
As mentioned in \ref{s:computation:problem}, several
algorithms\index{algorithm} may solve the same problem.\index{problem}
This immediately raises an important question: {\it which one should
we use?} In the clearest-cut case, there might be an algorithm which
takes less time and memory: it might be difficult to find it, but the
question has a well-defined answer. In most cases, there is a
trade-off\index{trade-off} between time and space: some algorithms may
take less time but more memory, and vice versa. We refer to time
measures as {\it time complexity}\index{complexity!time} and {\it
space complexity}.\index{complexity!space} Since RAM is generally
less costly than time, apart from a special cases time complexity is
used more often than space complexity. In the sequel, we almost always
mention complexity to mean ``time complexity''.
As programs consist of sequences of basic instructions, each of which
takes (almost) the same time to execute on the CPU, time complexity
evaluations usually count the number of instructions to be executed
before the program terminates. Space complexity evaluations count the
number of bytes of RAM that the program allocates whilst running. These
questions are, unfortunately, ill-defined: programs may behave well
with a given input and badly with another. Accordingly, we consider
three possibilities: {\it worst-case
complexity},\index{complexity!worst-case} {\it best-case
complexity},\index{complexity!best-case} and {\it average-case
complexity}.\index{complexity!average-case}
Best-case complexity is not often used: an algorithm may be very fast
on short or trivial input, but this says nothing about how the
algorithm will perform in general. Worst-case complexity is more
informative (as it gives a guarantee --- if an algorithm is fast in
the worst case, all the better for the general case!) and usually not
too difficult to evaluate: this is why it is the most studied
case. Average-case complexity is very informative, as it aims at the
general case, but it is often difficult to compute. And unless we can
also compute the variance attached to the average, it might be
misleading.
Below, we shall therefore mostly concentrate on worst-case time
complexity.
\subsubsection{Worst-case time complexity calculations}
\label{s:computation:timeworstcase}
We let $P$ be a program, and $t_P$ be the number of instructions that
are executed in $P$. Notice that, because of tests and loops, this is
different from the number of instructions actually written in the
program. The following rules-of-thumb hold.
\begin{itemize}
\item Basic assignments,\index{assignment} arithmetic/logical
operations and tests all have $t_P=1$.
\item If $P,Q$ are programs and $P;Q$ is their
concatenation,\index{concatenation} then
\begin{equation}
t_{P;Q} = t_P+t_Q. \label{eq:concatenation}
\end{equation}
\item If $T$ is a logical test\index{test} and $P,Q$ are programs, then
\begin{equation}
t_{\mbox{\scriptsize\tt if($T$)$P$\,else\,$Q$}} = t_T +
\max(t_P,t_Q).\label{eq:test}
\end{equation}
Notice that the use of the $\max$ operator implements the
worst-case\index{complexity!worst-case} policy; average- and best-case
would yield different formul{\ae}.
\end{itemize}
The case of the loop\index{loop} is more complicated, as it depends on
whether the body of the loop is independent on the
termination\index{termination} condition or not. Consider the
following algorithm $P$, where $Q$ is a program.
\begin{verbatim}
int i = 0;
while (i < n) {
Q();
i = i + 1;
}
\end{verbatim}
In this algorithm, $\mbox{\tt Q()}$ does not depend on $\mbox{\tt i}$,
and therefore we have $t_P = t_{\mbox{\scriptsize\tt i=0}} +
n(t_Q+t_{\mbox{\scriptsize\tt i$<$n}}+t_{\mbox{\scriptsize\tt i+1}}+
t_{\mbox{\scriptsize\tt i=$\cdot$}})+t_{\mbox{\scriptsize\tt
i$<$n}}=2+n(t_Q+3)$. The last test term refers to the test
$\mbox{\tt i}<\mbox{\tt n}$ when {\tt i} and {\tt n} have the same
value, which fails and allows the loop to terminate.
\subsubsection{Complexity orders}
\label{s:computation:complexityorder}
Suppose we are able to determine that $t_Q=\frac{1}{2}n$. Then
$t_P=\frac{1}{2}n^2+3n+1$. Since we would like to know the behaviour
of this algorithm in the worst-case,\index{complexity!worst-case} it
is interesting to look at the asymptotic behaviour of $t_P(n)$ for
$n\to\infty$. It is clear that the dominating term is
$\frac{1}{2}n^2$; moreover, asymptotically, the $\frac{1}{2}$
constant\index{constant} is not so important. We simply say that $t_P$
asymptotically behaves like $n^2$, and write it as $t_P\in O(n^2)$, or
``$t_P$ is $O(n^2)$''.\index{$O(\cdot)$}
In general, we say that a function\index{function} $f(n)$ is {\it
order\index{complexity!order} of $g(n)$} (and write it ``$f(n)$ is
$O(g(n))$'') if:
\begin{equation}
\exists c > 0 \quad \exists n_0\in\mathbb{N} \quad \forall n>n_0
\quad (f(n) \le c\, g(n)).
\end{equation}
In words: there are positive real $c$ and integer $n_0$ such that
$c\,g(n)$ dominates $f(n)$ for all $n>n_0$. Table \ref{tab:orders}
lists some complexity orders for various functions of $n$.
\begin{table}[!ht]
\begin{center}
\begin{tabular}{|l|l|} \hline
{\it Functions} & {\it Order} \\ \hline
$an+b$ with $a,b$ constants & $O(n)$ \\
polynomial of degree $d'$ in $n$ & $O(n^d)$ with $d\ge d'$ \\
$n+\log n$ & $O(n)$ \\
$n+\sqrt{n}$ & $O(n)$ \\
$\log n+\sqrt{n}$ & $O(\sqrt{n})$ \\
$n\log n^3$ & $O(n\log n)$ \\
$\frac{an+b}{cn+d}$, $a,b,c,d$ constants & $O(1)$ \\
\hline
\end{tabular}
\end{center}
\caption{Complexity orders of some functions of $n$.}
\label{tab:orders}
\end{table}
Evidently, an effort should be made to find the lowest possible
worst-case order, i.e.~although the function $2n+1$ is certainly
$O(n^4)$, it is much more informative to say that it is $O(n)$.
We remark that if $t_P(n)$ is a constant\index{constant} (i.e.~$n$
does not appear in the expression for $t_P$), then it is $O(1)$;
e.g.~looping $10^{100}$ times over an $O(1)$ program is itself $O(1)$.
%%%%%%%%%%%%%%%%%%%%%%%%%% CHAPTER: JAVA BASICS %%%%%%%%%%%%%%%%%%%%%%%%
%%%%%
\chapter{Java basics}
\label{c:java}
\begin{center}
\fbox{\begin{minipage}{13cm}{\small {\sc Abstract}. Short
introduction to Java. Variables, Objects, Classes, Interfaces,
and Data types. Functions, values and references. An example:
plotting the graph of a mathematical function on the screen. }
\end{minipage}}
\end{center}
Each computer brand --- or even model --- is different. CPU\index{CPU}
design and capabilities evolve in time, as does the set of
instructions\index{instruction} they can understand. On the other
hand, programmers spend a long time learning a programming
language,\index{language!programming} and once they are proficient in
one, they are unwilling to spend more time learning others. Thus,
languages should not change even though the underlying computer that
executes them will. This is attained in essentially two ways:
\begin{itemize}
\item updating the compiler\index{compiler} or
interpreter;\index{interpreter}
\item simulating a ``software computer'' that does not change.
\end{itemize}
The first paradigm is by far the most common. Since the instructions
that a CPU can actually execute are very different from the constructs
of human-employed programming languages, these must be translated into
executable code in order to be run. {\it Compilers}\index{compiler} or
{\it interpreters}\index{interpreter} are used for this task. A
compiler translates a user program at once, and writes a file
containing executable code. An interpreter translates the instructions
of a user program one after the other, following the program flow, and
executes each one immediately. Compiled languages are: C,\index{C}
C++,\index{C++} Pascal,\index{Pascal}, Fortran\index{Fortran},
(relatively) recent Basic\index{Basic} dialects, and many
others. Interpreted languages are: perl,\index{perl}
python,\index{python} early Basic dialects, and many
others. Typically, compiled languages yield code that is faster to
execute than interpreted languages; on the other hand, changing an
interpreted program is easier than changing a compiled one.
Java,\index{Java} on the other hand, rests on a piece of software that
simulates a virtual computer: in Java terms, this is a {\it Virtual
Machine} (VM).\index{virtual machine} The virtual machine can evolve
in time to take advantage of technical progress in computer design,
but always offers the same set of primitives to the programs it can
execute. This also makes it easy to port Java applications to
different platforms (e.g.~Windows,\index{Windows}
MacOSX,\index{MacOSX} Linux):\index{Linux} it suffices to implement an
appropriate VM.
\section{Development of a Java program}
\label{s:java:example}
A Java program is encoded in an ASCII\index{ASCII} text file ---
better use the first 128 characters and steer clear of accents. Open
your favourite text editor and type:
\begin{verbatim}
/*
Name: helloWorld.java
Purpose: a "hello world" program in Java
Author: Leo Liberti (from an idea by B. Kernighan)
Source: Java
History: 17/10/2011 work started
*/
class helloWorld {
public static void main( String [ ] args ) {
System.out.println("hello world");
}
}
\end{verbatim}
Save as {\tt helloWorld.java}. Now open a terminal window, and type:
\begin{verbatim}
javac helloWorld.java
java helloWorld
\end{verbatim}
The first command calls the Java compiler,\index{javac@{\tt
javac}}\index{java@{\tt java}} which translates the text above into
code that can be executed on the Java VM. The second command tells the
Java VM to execute this code. As an effect of the execution, the
computer should print {\tt hello world} on the same terminal as the
commands were issued.
\subsection{Variables}
\label{s:java:variables}
In Java, variable symbols\index{variable!symbol} can store
values\index{variable!value} or addresses.\index{variable!address}
Typically, variables having elementary data
types\index{data!type!elementary} such as {\tt boolean}, {\tt
int},\index{int@{\tt int}} {\tt long},\index{long@{\tt long}} {\tt
float},\index{float@{\tt float}} {\tt double},\index{double@{\tt double}} {\tt
char}\index{char@{\tt char}} store values: if {\tt int a} is a variable,
then its value is stored at a certain address in
memory.\index{memory!address} If {\tt myClass} is a user-defined
class,\index{class!user-defined} then the variable {\tt myClass C} has
a non-elementary data type:\index{data!type} in this case, Java stores
in {\tt C} a memory address, which points to a part of memory which
contains the actual value of {\tt C}.
\subsubsection{References}
Variables containing addresses are also called {\it
references}.\index{reference} Users need not concern themselves
excessively with storage implementation details, aside for a few (but
important) occurrences to do with copying data from a non-elementary
data typed variable to another. Will Java copy the addresses or the
values themselves? Copying addresses is known as {\it shallow
copy},\index{copy!shallow} whilst copying values is known as {\it
deep copy}.\index{copy!deep}
Consider a reference {\tt a} whose value is an address $a$ of a memory
cell containing the value $b$. This is represented graphically as
shown below.
\begin{center}
\begin{tikzpicture}
[memory/.style={rectangle,draw=black!50,fill=blue!20}]
\node at (0,0.5) [memory] (reference) {$a$};
\node at (0,0) {{\tt a}};
\node at (2,0.5) [memory] (address) {$b$};
\node at (2,0) {$a$};
\draw [->] (reference.east) -- (address.west);
\end{tikzpicture}
\end{center}
\subsection{Comments}
\label{s:java:comments}
A {\it comment}\index{comment} is simply text inserted in a program so
as to remind human readers of the meaning of the surrounding
instructions. Natural,\index{language!natural} rather than formal
languages,\index{language!formal} are usually employed. Comments are
supposed to make code clearer and easier to understand. A program with
no comments will probably be unreadable; on the other hand, users will
most likely ignore comments if every single line is commented.
In Java, comments can be single line or multi-line. A double slash
(``{\tt //}'') means that the rest of the line, until its end, will
contain a comment. A multi-line comment starts with ``{\tt /*}'' and
ends with ``{\tt */}''. An example of a multi-line comment is given in
the {\tt helloWorld} program.
Comments are ignored by the Java compiler,\index{compiler} but some
relevant information can be stored in comments, to be read by an
appropriate {\it preprocessor}\index{preprocessor} --- this is
software that interprets the program according to different rules, and
is usually called prior to (or independently of) the compiler. This
can be useful to automatically produce documentation for a given
software, for example.
\subsection{Classes}
A {\it class}\index{class} is the Java\index{Java} equivalent of a
mathematical set\index{set} defined by a property
$P$,\index{set!property} i.e.~$\{x\;|\;P(x)\}$. In Java, the property
$P$ is a description of the {\it data type}\index{data!type} of each
piece of data $x$ in the class, e.g.~$x$ might store an integer, a
float and a string.
In Java, every program must contain at least a class. A {\it
class}\index{class} is the formal Java definition of a data
structure.\index{data!structure} It usually contains a list of
variable names\index{variable!name} (with associated data
type)\index{data!type} and a list of functions that determine how the
values stored in the variables change. The class in the {\tt
helloWorld}\index{helloWorld@{\tt helloWorld}} program, called {\tt
helloWorld}, only contains one function called {\tt
main}.\index{main@{\tt main}}
A class is an entity which resides in the Java program. Once compiled
and executed, a class, strictly speaking, does nothing. The Java
VM,\index{virtual machine} however, may create (either by default or
because instructed to do so) {\it objects}\index{object} of any given
class. An object is therefore an instance of the class stored in
memory. If we draw a parallel between Java and mathematical language,
a class is to a set what an object is to an element. In other words, a
class is a description of the data structure, whereas an object is an
actual piece of data that is structured in memory according to the
specification of its class. For example, the class
\begin{verbatim}
class IntPair {
int first;
int second;
}
\end{verbatim}
defines a data structure\index{data!structure} that holds two integers
between $-2^{31}$ and $2^{31}-1$. An object {\tt myIntPair} of this
class, defined as:
\begin{verbatim}
IntPair myIntPair = new IntPair;
\end{verbatim}
holds a pair of integers in memory. The name {\tt myIntPair} is
arbitrary --- the fact that it is similar to the class name is only
supposed to help a reader identify the class directly from the object.
In general, two different objects of the same class hold different
data.
Class members,\index{class!member} be they data ({\it
attributes})\index{attribute} or functions ({\it
methods}),\index{method} can some specifiers, such as {\tt
public},\index{public} {\tt static}\index{static} and others. Public
class members can be referenced from instructions\index{instruction}
outside the class. Static members are stored at a single
address\index{memory!address} in memory, which means that all objects
of the same class all share static data.\index{data!shared} By
default, members are neither public nor static, which means that they
can only be referenced from instructions inside the class, and each
object of the class can refer to its own private\index{private} copy
of the data.
\subsubsection{The {\tt this} attribute}
Suppose the class {\tt myClass} has a method {\tt myMethod}. Within
the {\tt myMethod} code, the Java keyword {\tt this}\index{this@{\tt this}}
is a reference to the object which will execute {\tt myMethod}. This
means that two objects of the same class have the same attribute {\tt
this}, but this will hold two different memory addresses depending
on which object refers to it.
\subsubsection{Inheritance}\index{inheritance}\index{class!inheritance}
Just as sets can, in mathematics, be subsets of other sets, classes
can be subclasses of other classes. A class\index{class} {\tt C}
describing each of its objects\index{object} as storing an integer, a
float and a string might well be a subclass of another class {\tt B}
whose objects only store an integer and a float.
Inheritance is useful for several reasons. For example, if we need
both {\tt B} and {\tt C} in our code and do not have inheritance, we
must write
\begin{verbatim}
public class B {
int i;
float f;
}
public class C {
int i;
float f;
String s;
}
\end{verbatim}
Notice we are duplicating some code.\index{code!duplication} If we
need to change the {\tt float} to a {\tt double} later on, and still
require {\tt B} to be a subclass of {\tt C}, we must remember to
change the code in different places: since people forget such details,
it will very likely give rise to a bug.\index{bug} Notice that a
similar type of bug destroyed the Ariane\index{Ariane 5} 5 on its
maiden flight. Inheritance helps avoid this issue. We define
{\tt C} as follows:
\begin{verbatim}
public class C extends B {
String s;
}
\end{verbatim}
In other words, we explicitly tell the compiler\index{compiler} that
there is a relationship between the two classes. This not only
shortens the code, but decreases the chances of coding mistakes by
delegating to the compiler the responsibility of checking that the
relationship $\mbox{\tt C}\subseteq\mbox{\tt B}$ is maintained
throughout the code.
\subsubsection{Interfaces}
\label{s:java:interface}
An {\it interface}\index{interface}\index{class!interface} is a very
special kind of class, whose purpose is that of enforcing
conformance\index{conformance} to a certain class
structure.\index{class!structure} For example, in a Graphical User
Interface (GUI)\index{GUI} every window (including full program
windows, dialog boxes and warning boxes) must conform to certain basic
notions about windows: e.g., they possess a width, a height, a title
and a frame, they have some standard buttons for minimizing,
maximizing and closing, they have some standard pull-down menu, and
they must remember their contents so that these can be re-drawn if
another window is temporarily dragged over it. A programmer who
designs a new type of window might be tempted to design a window of a
different kind, say with no standard buttons. However, all other
programs running on the GUI automatically assume that all windows have
standard buttons, so they are free to call the associated code: in the
long run, this might cause bugs and unforeseen behaviour. To avoid
this, the compiler itself enforces conformance with a standard idea of
window in the GUI by means of an interface: all classes defining a
window must inherit from the window interface, and implement its
functions as they see fit.
Remark that interfaces have no data and only contain the names,
argument types and return types of the member functions. No object can
be defined as member of an interface class
only.\index{object!interface} By contrast, objects of different
classes that both implement\index{interface!implementation} (i.e.,
inherit from) the same interface class can both be attributed the
interface data type. Let us consider the example of a normal window
and of a special type of window whose aspect ratio is always 3:2.
\begin{verbatim}
interface Window {
int getWidth();
int getHeight();
}
class MainWindow implements Window {
int width;
int height;
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
class FixedRatioWindow implements Window {