He aquí las respuestas a las tareas propuestas:1. Bubble sort tiene un tiempo asintótico de O(n^2) en el peor caso, ya que requiere n pasadas sobre el arreglo y en cada pasada se comparan (n-1) elementos. Merge sort tiene un tiempo asintótico de O(n log n), lo que lo hace más escalable para grandes valores de n. Preferiría merge sort porque su complejidad es menor, especialmente para ordenar grandes cantidades de datos. 2. Sí, una búsqueda binaria puede implementarse siguiendo el paradigma divide y
The document describes the merge sort algorithm. It explains that merge sort uses a divide and conquer approach to sort an array. It works by recursively splitting the array into smaller sub-arrays of size n/2 until the sub-arrays contain a single element, which is trivially sorted. It then merges the sorted sub-arrays back together to produce the final sorted array. The time complexity of merge sort is O(n log n) as it recursively solves two subproblems of size n/2 at each step. This makes merge sort more efficient than insertion sort, which has a worst-case time of O(n2), especially for large problem sizes.
Similar to He aquí las respuestas a las tareas propuestas:1. Bubble sort tiene un tiempo asintótico de O(n^2) en el peor caso, ya que requiere n pasadas sobre el arreglo y en cada pasada se comparan (n-1) elementos. Merge sort tiene un tiempo asintótico de O(n log n), lo que lo hace más escalable para grandes valores de n. Preferiría merge sort porque su complejidad es menor, especialmente para ordenar grandes cantidades de datos. 2. Sí, una búsqueda binaria puede implementarse siguiendo el paradigma divide y
Similar to He aquí las respuestas a las tareas propuestas:1. Bubble sort tiene un tiempo asintótico de O(n^2) en el peor caso, ya que requiere n pasadas sobre el arreglo y en cada pasada se comparan (n-1) elementos. Merge sort tiene un tiempo asintótico de O(n log n), lo que lo hace más escalable para grandes valores de n. Preferiría merge sort porque su complejidad es menor, especialmente para ordenar grandes cantidades de datos. 2. Sí, una búsqueda binaria puede implementarse siguiendo el paradigma divide y (20)
He aquí las respuestas a las tareas propuestas:1. Bubble sort tiene un tiempo asintótico de O(n^2) en el peor caso, ya que requiere n pasadas sobre el arreglo y en cada pasada se comparan (n-1) elementos. Merge sort tiene un tiempo asintótico de O(n log n), lo que lo hace más escalable para grandes valores de n. Preferiría merge sort porque su complejidad es menor, especialmente para ordenar grandes cantidades de datos. 2. Sí, una búsqueda binaria puede implementarse siguiendo el paradigma divide y
1. Merge-Sort
Técnica: Divide y Vencerás
Ing. Juan Ignacio Zamora M. MS.c
Facultad de Ingenierías
Licenciatura en Ingeniería Informática con Énfasis en Desarrollo de Software
Universidad Latinoamericana de Ciencia y Tecnología
T(n/2) T(n/2)
• For each of the size-n/2 subproblems, we
problems, each costing T (n/4):
cn
cn/2
T(n/4) T(n/4)
cn/2
T(n/4) T(n/4)
• Continue expanding until the problem sizes
Ö
lg n
n
c c c c c c
cn
cn/2
cn/4 cn/4
cn/2
cn/4 cn
2. Técnica: Divide y Vencerás
¤ Técnica para resolución de problemas
computaciones por medio de la
descomposición del problema en instancias
equivalentes pero de menor tamaño.
¤ La técnica se basa en 3 pasos conceptuales
¤ Dividir el problema en sub problemas
¤ Conquistar cada problema de forma recursiva
¤ Combinar todas las soluciones para solucionar
el problema original
3. Merge Sort
Pseudo-Codigo
Merge-Sort (A, p, r)
If ( p < r ) Condición Base
q = [(p + r) / 2] Dividir
Merge-Sort(A, p, q) Conquistar (por Izq)
Merge-Sort(A, q + 1, r) Conquistar (por Derecha)
Merge(A, p, q, r) Combinar
Condición Base: condición que decide el momento adecuado para solventar el problema a fuerza bruta
5. Solución por Recursión “Bottom Up”
point of p and r as their average (p + r)/2. We of course have to take the
to ensure that we get an integer index q. But it is common to see students per
calculations like p + (r − p)/2, or even more elaborate expressions, forgettin
easy way to compute an average.]
Example: Bottom-up view for n = 8: [Heavy lines demarcate subarrays us
subproblems.]
1 2 3 4 5 6 7 8
5 2 4 7 1 3 2 6
2 5 4 7 1 3 2 6
initial array
merge
2 4 5 7 1 2 3 6
merge
1 2 3 4 5 6 7
merge
sorted array
2
1 2 3 4 5 6 7 8
2-10 Lecture Notes for Chapter 2: Getting Started
[Examples when n is a power of 2 are most s
also want an example when n is not a power of
Bottom-up view for n = 11:
1 2 3 4 5 6 7 8
4 7 2 6 1 4 7 3
initial array
merge
merge
merge
sorted array
5 2 6
9 10 11
4 7 2 1 6 4 3 7 5 2 6
2 4 7 1 4 6 3 5 7 2 6
1 2 4 4 6 7 2 3 5 6 7
1 2 2 3 4 4 5 6 6 7 7
1 2 3 4 5 6 7 8 9 10 11
merge
[Here, at the next-to-last level of recursion, so
[Ejercicio] Inténtelo Ud.: Use Merge-Sort para A = {8,5,3,2,1,4,9,11,12}
Demuéstrelo en una hoja de papel
6. Combinar : Merge Step
¤ Merge (A, p, q, r) donde
¤ p <= q < r
¤ Tiempo asintótico O(n) donde
n = r – p + 1
¤ Salida: 2 arreglos son
combinados en un único
arreglo
• The only way that ∞ cannot lose is when both piles have ∞ exposed as their
top cards.
• But when that happens, all the nonsentinel cards have already been placed into
the output pile.
• We know in advance that there are exactly r − p + 1 nonsentinel cards ⇒ stop
once we have performed r − p + 1 basic steps. Never a need to check for
sentinels, since theyíll always lose.
• Rather than even counting basic steps, just fill up the output array from index p
up through and including index r.
Pseudocode:
MERGE(A, p, q, r)
n1 ← q − p + 1
n2 ← r − q
create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]
for i ← 1 to n1
do L[i] ← A[p + i − 1]
for j ← 1 to n2
do R[ j] ← A[q + j]
L[n1 + 1] ← ∞
R[n2 + 1] ← ∞
i ← 1
j ← 1
for k ← p to r
do if L[i] ≤ R[ j]
then A[k] ← L[i]
i ← i + 1
else A[k] ← R[ j]
j ← j + 1
[The book uses a loop invariant to establish that MERGE works correctly. In a
7. Merge(A, 9, 12, 16)2-12 Lecture Notes for Chapter 2: Getting Started
Example: A call of MERGE(9, 12, 16)
A
L R
1 2 3 4 1 2 3 4
i j
k
2 4 5 7 1 2 3 6
A
L R
1 2 3 4 1 2 3 4
i j
k
2 4 5 7
1
2 3 61
2 4 5 7 1 2 3 6 4 5 7 1 2 3 6
A
L R
9 10 11 12 13 14 15 16
1 2 3 4 1 2 3 4
i j
k
2 4 5 7
1
2 3 61
5 7 1 2 3 62 A
L R
1 2 3 4 1 2 3 4
i j
k
2 4 5 7
1
2 3 61
7 1 2 3 62 2
5
∞
5
∞
5
∞
5
∞
5
∞
5
∞
5
∞
5
∞
9 10 11 12 13 14 15 16
9 10 11 12 13 14 15 16
9 10 11 12 13 14 15 168
Ö
17
Ö
8
Ö
17
Ö
8
Ö
17
Ö
8
Ö
17
Ö
A
L R
1 2 3 4 1 2 3 4
i j
k
2 4 5 7
1
2 3 61
1 2 3 62 2 3 A
L R
1 2 3 4 1 2 3 4
i j
k
2 4 5 7
1
2 3 61
2 3 62 2 3 4
A
L R
1 2 3 4 1 2 3 4
i j
k
2 4 5 7
1
2 3 61
3 62 2 3 4 5 A
L R
1 2 3 4 1 2 3 4
i j
k
2 4 5 7
1
2 3 61
62 2 3 4 5
5
∞
5
∞
5
∞
5
∞
5
∞
5
∞
5
∞
5
∞
6
A
L R
1 2 3 4 1 2 3 4
i j
k
2 4 5 7
1
2 3 61
72 2 3 4 5
5
∞
5
∞
6
9 10 11 12 13 14 15 16
9 10 11 12 13 14 15 16
9 10 11 12 13 14 15 16
9 10 11 12 13 14 15 16
9 10 11 12 13 14 15 16
8
Ö
17
Ö
8
Ö
17
Ö
8
Ö
17
Ö
8
Ö
17
Ö
8
Ö
17
Ö
Merge(A, p, q, r )
8. Rendimiento Merge-Sort
¤ El rendimiento T(n) esta determinado por la recurrencia del algoritmo.
¤ Merge-Sort se compone de los 3 pasos del paradigma (divide y
vencerás) y por ende estos definen su rendimiento.
¤ Si un arreglo se descompone en “a” sub problemas, esto indica que
cada elemento es “1/b” del problema original. Para Merge Sort, tanto
“a” como “b” equivalen a 2.
¤ Por tanto Merge-Sort se compone de T(n/b) problemas que ocurren
“a” veces; por tanto se dice que toma aT(n/b) resolver “a”.
¤ D(n) representa el tiempo que toma dividirlo en sub problemas
¤ C(n) representa el tiempo que toma combinar los sub problemas
resueltos.
T(n) =
Θ(1)
aT(n / b)+ D(n)+C(n)
n ≤ c
9. Rendimiento Merge-Sort
¤ Por tanto si n > 1
¤ Dividir: el tiempo que toma dividir el array en 2 = D(n) = O(1)
¤ Conquistar: recursivamente se solucionan 2 sub problemas,
cada uno de tamaño n/2… por tanto se dice que su tiempo
es igual a 2 x T(n/2) = 2T(n/2).
¤ Combinar: el procedimiento Merge, ya sabemos que toma
C(n) = O(n) resolverlo.
¤ Entonces… como dividir toma tiempo constante
decimos que
T (n/b) time to solve ⇒ we spend aT (n/b) time solving subproblems.
• Let the time to combine solutions be C(n).
• We get the recurrence
T (n) =
(1) if n ≤ c ,
aT(n/b) + D(n) + C(n) otherwise .
Analyzing merge sort
For simplicity, assume that n is a power of 2 ⇒ each divide step yields two sub-
problems, both of size exactly n/2.
The base case occurs when n = 1.
When n ≥ 2, time for merge sort steps:
Divide: Just compute q as the average of p and r ⇒ D(n) = (1).
Conquer: Recursively solve 2 subproblems, each of size n/2 ⇒ 2T(n/2).
Combine: MERGE on an n-element subarray takes (n) time ⇒ C(n) = (n).
Since D(n) = (1) and C(n) = (n), summed together they give a function that
is linear in n: (n) ⇒ recurrence for merge sort running time is
T(n) =
(1) if n = 1 ,
2T (n/2) + (n) if n > 1 .
Solving the merge-sort recurrence: By the master theorem in Chapter 4, we can
2-14 Lecture Notes for Chapter 2: Getting Started
• Let c be a constant that describes the runn
is the time per array element for the divide
cannot necessarily use the same constant fo
detail at this point.]
• We rewrite the recurrence as
T(n) =
c if n = 1 ,
2T (n/2) + cn if n > 1 .
• Draw a recursion tree, which shows succes
•
Donde c equivale el tiempo constante que toma el caso base
10. Insertion-Sort vs. Merge-Sort
¤ Insertion-Sort en su peor escenario tiene la duración de
¤ Según el “Master Teorem” se puede definir que los problemas
recurrentes tienen tiempo de duración
O(n lg n) donde lg n == log en base 2 de n. Por tanto Merge-Sort
tiene tiempo
ively solve 2 subproblems, each of size n/2 ⇒ 2T(n/2).
E on an n-element subarray takes (n) time ⇒ C(n) = (n).
1) and C(n) = (n), summed together they give a function that
) ⇒ recurrence for merge sort running time is
if n = 1 ,
+ (n) if n > 1 .
-sort recurrence: By the master theorem in Chapter 4, we can
urrence has the solution T(n) = (n lg n). [Reminder: lg n
tion sort ( (n2
) worst-case time), merge sort is faster. Trading
factor of lg n is a good deal.
nsertion sort may be faster. But for large enough inputs, merge
e faster, because its running time grows more slowly than inser-
how to solve the merge-sort recurrence without the master the-
T(n) =
(1) if n = 1 ,
2T (n/2) + (n) if n > 1 .
Solving the merge-sort recurrence: By t
show that this recurrence has the solutio
stands for log2 n.]
Compared to insertion sort ( (n2
) worst-c
a factor of n for a factor of lg n is a good d
On small inputs, insertion sort may be fas
sort will always be faster, because its runn
tion sortís.
We can understand how to solve the merge
orem.
Merge Sort, crece mucho
mas lento que Insertion-Sort.
Esto se vuelve mas notable
conforme “n” incremente su
tamaño.
ursively solve 2 subproblems, each of size n/2 ⇒ 2T(n/2).
RGE on an n-element subarray takes (n) time ⇒ C(n) = (n).
(1) and C(n) = (n), summed together they give a function that
(n) ⇒ recurrence for merge sort running time is
if n = 1 ,
2) + (n) if n > 1 .
ge-sort recurrence: By the master theorem in Chapter 4, we can
ecurrence has the solution T(n) = (n lg n). [Reminder: lg n
.]
sertion sort ( (n2
) worst-case time), merge sort is faster. Trading
a factor of lg n is a good deal.
, insertion sort may be faster. But for large enough inputs, merge
be faster, because its running time grows more slowly than inser-
nd how to solve the merge-sort recurrence without the master the-
f p and r ⇒ D(n) = (1).
ems, each of size n/2 ⇒ 2T(n/2).
array takes (n) time ⇒ C(n) = (n).
summed together they give a function that
erge sort running time is
the master theorem in Chapter 4, we can
on T(n) = (n lg n). [Reminder: lg n
t-case time), merge sort is faster. Trading
deal.
aster. But for large enough inputs, merge
nning time grows more slowly than inser-
11. Merge-Sort es el campeón de la
semana.
Próximos contendientes … Heap-Sort, Quick-Sort…
12. Tarea
Problemas de la Semana
1. Programar el algoritmo de
“BubleSort” en su lenguaje de
preferencia. Calcular el tiempo
asintótico y compararlo contra
MergeSort. Cual prefiere?
Explique su respuesta!
Continua…
13. Tarea
Problemas de la Semana
2. Demuestre con argumentos lógicos si
una búsqueda binaria puede ser escrita
bajo el paradigma de divide y
venceras…? (pista revisar capitulo 12)
3. Calcular el tiempo asintótico de los
problemas [Carry Operations, Jolly
Jumper y el Palíndromo de 2 números de
3 dígitos.
4. Leer Capítulos 4 (divide and conquer), 6 (heapsort) y 7 (quicksort).
14. Temas de Exposición Grupal
¤ Algoritmo Torres de Hanói
¤ “Divide and Conquer” orientado a Parallel Programming << ejemplo: Merge Sort Multihilo >>
¤ Algoritmo de Disjktra
¤ Transformación de Fourier*
¤ Radix-Sort
¤ Bucket-Sort
¤ Geometría Computacional*
¤ String Matching con Autómatas Finitos*
¤ Multiplicación Binaria usando “Divide and Conquer”
¤ Algoritmo Bellman-Ford*