1. ì
Insertion
Sort
Ing.
Juan
Ignacio
Zamora
M.
MSc.
|
Universidad
La8noamericana
de
Ciencia
y
Tecnología
2. La
leyenda
de
Gauss
ì Érase
una
vez
un
niño
alemán
llamado
Carl
Friedrich
Gauss.
Cuando
tenía
diez
años,
en
1787,
su
profesor
de
la
escuela,
enfadado
porque
sus
alumnos
se
portaban
mal,
le
puso
un
problema
matemá8co
al
pequeño
Carl
y
a
sus
compañeros.
ì Los
niños
debían
sumar
todos
los
números
del
1
al
100;
es
decir,
1+2=3+3=6+4=10+5=15+6=21
y
así
sucesivamente
hasta
sumar
los
100
ì El
profesor
se
sentó
en
su
silla
a
leer
el
periódico,
confiaba
en
que
tendría
horas
hasta
que
los
niños
sumaran
todos
los
números….
4. Como
lo
hizo?
ì Sea
la
progresión
S
=
a……m…….p…….u
cuya
razón
esta
definida
por
r.
ì Entonces
S
=
a+b+c………….+l+m+u
ì También
S
=
u+m+l………….+c+b+a
ì Entonces
2S
=
(a+u)
+
(b+m)
+
(c+l)
+
(l+c)
+
(m+b)
+
(u+a).
ì Todos
los
binomios
anteriores
son
iguales
a
(a+u).
Recuerde
que
a
es
el
primer
termino
y
u
el
ul8mo.
ì Esto
quiere
decir
que
la
la
suma
de
la
progresión
es
(a+u)
“n”
veces.
Ósea,
(a+u)n
y
esto
se
divide
entre
2
ya
que
todos
los
términos
se
cuentan
2
veces
por
tanto:
S =
(a +u)n
2
5. Probemos
el
Teorema
S =1+ 2 +3.......+ 98+ 99 +100
S =100 + 99 + 98.......+3+ 2 +1
2S =101+101+101.......+101+101+101
S =
(a +u)n
2
S =
(1+100)100
2
=
(101)100
2
= 5050
6. Progresiones
Aritméticas
ì Es
toda
serie
es
la
cual
cada
termino
después
del
primero
se
ob8ene
sumándole
al
termino
anterior
una
can8dad
constante.
ì S
=1,
3,
5,
7
….
Donde
la
razón
r
o
diferencia
d
es
2,
ya
que
3-‐1=
2
à
esto
implica
que
la
razón
(r)
es
la
diferencia
entre
un
termino
cualquiera
menos
el
anterior.
7. Deducción
de
la
formula
del
enésimo
termino
ì Sea
la
progresión
S
=
a,
b,
c
,d……….u,
en
donde
“u”
es
el
enésimo
termino
y
cuya
razón
es
“r”
ì Entonces
tenemos
que
ì b
=
a
+
r
ì c
=
b
+
r
à
(a
+
r)
+
r
=
a
+
2r
ì d
=
c
+
r
à
(a
+
2r)
+
r
=
a
+
3r
ì Entonces
cada
termino
es
igual
al
primer
termino
de
la
progresión
mas
la
razón
como
términos
le
preceden.
ì Sabemos
que
el
primer
termino
es
“a”
y
le
preceden
(n-‐1)
términos
donde
la
razón
esta
dada
por
“r”,
entonces
podemos
concluir
que
u = a +(n −1)r
8. Deducción
de
la
formula
del
enésimo
termino
ì Volviendo
al
ejemplo
del
pequeño
Gauss,
tenemos
que
S
=
5050,
el
primer
termino
“a”
es
1
y
que
la
razón
“r”
es
1
ya
que
se
suma
de
uno
en
uno
y
que
la
can8dad
(n)
de
términos
es
100.
ì Con
esto
respaldamos
el
teorema
de
Gauss.
ì Inténtelo
Ud:
ì Hallar
el
15vo
termino
de
la
sucesión
4,
7,
10…..
ì El
15vo
termino
es
no
representa
la
suma
de
los
términos,
solamente
representa
su
valor.
u = a +(n −1)r u =1+(100 −1)1=100
10. Pseudo-‐Codigo
::
InsertionSort
1 2 3 4 5 6
2 4 5 6 1 3(d)
1 2 3 4 5 6
2 4 5 61 3(e)
1 2 3 4 5 6
2 4 5 61 3(f)
Figure 2.2 The operation of INSERTION-SORT on the array A D h5; 2; 4; 6; 1; 3i. Array indi
appear above the rectangles, and values stored in the array positions appear within the rectang
(a)–(e) The iterations of the for loop of lines 1–8. In each iteration, the black rectangle holds
key taken from AŒj, which is compared with the values in shaded rectangles to its left in the tes
line 5. Shaded arrows show array values moved one position to the right in line 6, and black arro
indicate where the key moves to in line 8. (f) The final sorted array.
INSERTION-SORT.A/
1 for j D 2 to A:length
2 key D AŒj
3 // Insert AŒj into the sorted sequence AŒ1 : : j 1.
4 i D j 1
5 while i > 0 and AŒi > key
6 AŒi C 1 D AŒi
7 i D i 1
8 AŒi C 1 D key
18 Chapter 2 Getting Started
1 2 3 4 5 6
5 2 4 6 1 3(a)
1 2 3 4 5 6
2 5 4 6 1 3(b)
1 2 3 4 5 6
2 4 5 6 1 3(c)
1 2 3 4 5 6
2 4 5 6 1 3(d)
1 2 3 4 5 6
2 4 5 61 3(e)
1 2 3 4 5 6
2 4 5 61 3(f)
Figure 2.2 The operation of INSERTION-SORT on the array A D h5; 2; 4; 6; 1; 3i. Array indices
appear above the rectangles, and values stored in the array positions appear within the rectangles.
(a)–(e) The iterations of the for loop of lines 1–8. In each iteration, the black rectangle holds the
key taken from AŒj, which is compared with the values in shaded rectangles to its left in the test of
line 5. Shaded arrows show array values moved one position to the right in line 6, and black arrows
indicate where the key moves to in line 8. (f) The final sorted array.
INSERTION-SORT.A/
1 for j D 2 to A:length
2 key D AŒj
3 // Insert AŒj into the sorted sequence AŒ1 : : j 1.
4 i D j 1
5 while i > 0 and AŒi > key
MIT
Chapter
2
–
pag
18
11. Tiempo
de
Ejecución
de
InsertionSort
26 Chapter 2 Getting Started
INSERTION-SORT.A/ cost times
1 for j D 2 to A:length c1 n
2 key D AŒj c2 n 1
3 // Insert AŒj into the sorted
sequence AŒ1 : : j 1. 0 n 1
4 i D j 1 c4 n 1
5 while i > 0 and AŒi > key c5
Pn
jD2 tj
6 AŒi C 1 D AŒi c6
Pn
jD2.tj 1/
7 i D i 1 c7
Pn
jD2.tj 1/
8 AŒi C 1 D key c8 n 1
The running time of the algorithm is the sum of running times for each state-
ment executed; a statement that takes ci steps to execute and executes n times will
contribute ci n to the total running time.6
To compute T .n/, the running time of
INSERTION-SORT on an input of n values, we sum the products of the cost and
times columns, obtaining
T .n/ D c1n C c2.n 1/ C c4.n 1/ C c5
nX
tj C c6
nX
.tj 1/
26 Chapter 2 Getting Started
INSERTION-SORT.A/ cost times
1 for j D 2 to A:length c1 n
2 key D AŒj c2 n 1
3 // Insert AŒj into the sorted
sequence AŒ1 : : j 1. 0 n 1
4 i D j 1 c4 n 1
5 while i > 0 and AŒi > key c5
Pn
jD2 tj
6 AŒi C 1 D AŒi c6
Pn
jD2.tj 1/
7 i D i 1 c7
Pn
jD2.tj 1/
8 AŒi C 1 D key c8 n 1
The running time of the algorithm is the sum of running times for each state-
ment executed; a statement that takes ci steps to execute and executes n times will
contribute ci n to the total running time.6
To compute T .n/, the running time of
INSERTION-SORT on an input of n values, we sum the products of the cost and
times columns, obtaining
T .n/ D c1n C c2.n 1/ C c4.n 1/ C c5
nX
jD2
tj C c6
nX
jD2
.tj 1/
C c7
nX
jD2
.tj 1/ C c8.n 1/ :
Donde
el
Tiempo
T
para
una
progresión
n
esta
dado
por:
12. Tiempo
de
Ejecución
de
InsertionSort
ì El
Mejor
Tiempo
de
Ejecución
ì Por
tanto
y
en
resumen
esta
ecuación
se
comporta
como
una
función
lineal
de
n.
T .n/ D c1n C c2.n 1/ C c4.n 1/ C c5
jD2
tj C c6
jD2
.tj 1/
C c7
nX
jD2
.tj 1/ C c8.n 1/ :
Even for inputs of a given size, an algorithm’s running time may depend
which input of that size is given. For example, in INSERTION-SORT, the
case occurs if the array is already sorted. For each j D 2; 3; : : : ; n, we then
that AŒi Ä key in line 5 when i has its initial value of j 1. Thus tj D 1
j D 2; 3; : : : ; n, and the best-case running time is
T .n/ D c1n C c2.n 1/ C c4.n 1/ C c5.n 1/ C c8.n 1/
D .c1 C c2 C c4 C c5 C c8/n .c2 C c4 C c5 C c8/ :
We can express this running time as an C b for constants a and b that depend
the statement costs ci ; it is thus a linear function of n.
If the array is in reverse sorted order—that is, in decreasing order—the w
case results. We must compare each element AŒj with each element in the en
sorted subarray AŒ1 : : j 1, and so tj D j for j D 2; 3; : : : ; n. Noting that
6This characteristic does not necessarily hold for a resource such as memory. A statement
references m words of memory and is executed n times does not necessarily reference mn dis
words of memory.
T(n) = an + b
Ω(n) = an + b
13. Tiempo
de
Ejecución
de
InsertionSort
ì El
Peor
Tiempo
de
Ejecución
ì Esta
función
se
comporta
de
forma
cuadrá8ca
de
n
2.2 Analyzing algorithms 27
nX
jD2
j D
n.n C 1/
2
1
and
nX
jD2
.j 1/ D
n.n 1/
2
(see Appendix A for a review of how to solve these summations), we find that in
the worst case, the running time of INSERTION-SORT is
T .n/ D c1n C c2.n 1/ C c4.n 1/ C c5
Â
n.n C 1/
2
1
Ã
C c6
Â
n.n 1/
2
Ã
C c7
Â
n.n 1/
2
Ã
C c8.n 1/
D
c5
2
C
c6
2
C
c7
2
Á
n2
C c1 C c2 C c4 C
c5
2
c6
2
c7
2
C c8
Á
n
.c2 C c4 C c5 C c8/ :
We can express this worst-case running time as an2
C bn C c for constants a, b,
and c that again depend on the statement costs ci ; it is thus a quadratic function
of n.
Typically, as in insertion sort, the running time of an algorithm is fixed for a
given input, although in later chapters we shall see some interesting “randomized”
algorithms whose behavior can vary even for a fixed input.
Worst-case and average-case analysis
In our analysis of insertion sort, we looked at both the best case, in which the input
2.2 Analyzing algorithms 27
nX
j D2
j D
n.n C 1/
2
1
and
nX
j D2
.j 1/ D
n.n 1/
2
(see Appendix A for a review of how to solve these summations), we find that in
the worst case, the running time of INSERTION-SORT is
T .n/ D c1n C c2.n 1/ C c4.n 1/ C c5
Â
n.n C 1/
2
1
Ã
C c6
Â
n.n 1/
2
Ã
C c7
Â
n.n 1/
2
Ã
C c8.n 1/
D
c5
2
C
c6
2
C
c7
2
Á
n2
C c1 C c2 C c4 C
c5
2
c6
2
c7
2
C c8
Á
n
.c2 C c4 C c5 C c8/ :
We can express this worst-case running time as an2
C bn C c for constants a, b,
and c that again depend on the statement costs ci ; it is thus a quadratic function
of n.
Typically, as in insertion sort, the running time of an algorithm is fixed for a
given input, although in later chapters we shall see some interesting “randomized”
algorithms whose behavior can vary even for a fixed input.
Ο(n) = an2
+ bn +cT(n) = an2
+ bn +c
Mejor
vs
Peor