SlideShare a Scribd company logo
1 of 14
Download to read offline
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
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
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
Demostración Conceptual
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
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
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 )
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
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
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-
Merge-Sort es el campeón de la
semana.
Próximos contendientes … Heap-Sort, Quick-Sort…
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…
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).
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*

More Related Content

What's hot

Español estructurado
Español estructuradoEspañol estructurado
Español estructuradoJorge Garcia
 
Ejercicios propuestos de dependencia e independencia lineal
Ejercicios propuestos de dependencia e independencia linealEjercicios propuestos de dependencia e independencia lineal
Ejercicios propuestos de dependencia e independencia linealalgebra
 
ejercicios de recorrido de grafos (arboles)
ejercicios de recorrido de grafos (arboles) ejercicios de recorrido de grafos (arboles)
ejercicios de recorrido de grafos (arboles) brayan0015
 
Sistema de Ecuaciones diferenciales
Sistema de Ecuaciones diferencialesSistema de Ecuaciones diferenciales
Sistema de Ecuaciones diferencialesKike Prieto
 
Estructura de Datos: Recursividad
Estructura de Datos: RecursividadEstructura de Datos: Recursividad
Estructura de Datos: RecursividadYanahui Bc
 
Coeficientes indeterminados
Coeficientes indeterminadosCoeficientes indeterminados
Coeficientes indeterminadosJorgearturofrias
 
Determinantes De Dos Columnas Por N Filas
Determinantes De Dos Columnas Por N FilasDeterminantes De Dos Columnas Por N Filas
Determinantes De Dos Columnas Por N Filasgerarjam
 
Campos vectoriales
Campos vectorialesCampos vectoriales
Campos vectorialesortari2014
 
Análisis de complejidad introducción notación big o
Análisis de complejidad   introducción notación big oAnálisis de complejidad   introducción notación big o
Análisis de complejidad introducción notación big oUVM
 
Reporte de practica sumador binario
Reporte de practica sumador binarioReporte de practica sumador binario
Reporte de practica sumador binarioDiego Ramírez
 
Ordenamiento con árbol binario
Ordenamiento con árbol binarioOrdenamiento con árbol binario
Ordenamiento con árbol binarioMauricio Solano
 
Ejercicios resueltos de c++
Ejercicios resueltos de c++Ejercicios resueltos de c++
Ejercicios resueltos de c++Jhon TRUJILLO
 
Características de sumadores, codificadores, decodificadores, multiplexores y...
Características de sumadores, codificadores, decodificadores, multiplexores y...Características de sumadores, codificadores, decodificadores, multiplexores y...
Características de sumadores, codificadores, decodificadores, multiplexores y...Miguel Brunings
 
20 ejercicios propuestos
20 ejercicios propuestos20 ejercicios propuestos
20 ejercicios propuestosSykesPonce
 

What's hot (20)

Español estructurado
Español estructuradoEspañol estructurado
Español estructurado
 
Ejercicios propuestos de dependencia e independencia lineal
Ejercicios propuestos de dependencia e independencia linealEjercicios propuestos de dependencia e independencia lineal
Ejercicios propuestos de dependencia e independencia lineal
 
Funciones recursivas
Funciones recursivasFunciones recursivas
Funciones recursivas
 
ejercicios de recorrido de grafos (arboles)
ejercicios de recorrido de grafos (arboles) ejercicios de recorrido de grafos (arboles)
ejercicios de recorrido de grafos (arboles)
 
Brute force
Brute forceBrute force
Brute force
 
Sistema de Ecuaciones diferenciales
Sistema de Ecuaciones diferencialesSistema de Ecuaciones diferenciales
Sistema de Ecuaciones diferenciales
 
Árboles
ÁrbolesÁrboles
Árboles
 
Estructura de Datos: Recursividad
Estructura de Datos: RecursividadEstructura de Datos: Recursividad
Estructura de Datos: Recursividad
 
Coeficientes indeterminados
Coeficientes indeterminadosCoeficientes indeterminados
Coeficientes indeterminados
 
Determinantes De Dos Columnas Por N Filas
Determinantes De Dos Columnas Por N FilasDeterminantes De Dos Columnas Por N Filas
Determinantes De Dos Columnas Por N Filas
 
Campos vectoriales
Campos vectorialesCampos vectoriales
Campos vectoriales
 
Análisis de complejidad introducción notación big o
Análisis de complejidad   introducción notación big oAnálisis de complejidad   introducción notación big o
Análisis de complejidad introducción notación big o
 
Reporte de practica sumador binario
Reporte de practica sumador binarioReporte de practica sumador binario
Reporte de practica sumador binario
 
Pseint
PseintPseint
Pseint
 
Ordenamiento con árbol binario
Ordenamiento con árbol binarioOrdenamiento con árbol binario
Ordenamiento con árbol binario
 
Diagramas de Flujo con DFD.
Diagramas de Flujo con DFD.Diagramas de Flujo con DFD.
Diagramas de Flujo con DFD.
 
Notacion Asintotica
Notacion AsintoticaNotacion Asintotica
Notacion Asintotica
 
Ejercicios resueltos de c++
Ejercicios resueltos de c++Ejercicios resueltos de c++
Ejercicios resueltos de c++
 
Características de sumadores, codificadores, decodificadores, multiplexores y...
Características de sumadores, codificadores, decodificadores, multiplexores y...Características de sumadores, codificadores, decodificadores, multiplexores y...
Características de sumadores, codificadores, decodificadores, multiplexores y...
 
20 ejercicios propuestos
20 ejercicios propuestos20 ejercicios propuestos
20 ejercicios propuestos
 

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

5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquerKrish_ver2
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquerVikas Sharma
 
Admission in india 2015
Admission in india 2015Admission in india 2015
Admission in india 2015Edhole.com
 
T2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptxT2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptxGadaFarhan
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1Amrinder Arora
 
5.2 divede and conquer 03
5.2 divede and conquer 035.2 divede and conquer 03
5.2 divede and conquer 03Krish_ver2
 
5.2 divede and conquer 03
5.2 divede and conquer 035.2 divede and conquer 03
5.2 divede and conquer 03Krish_ver2
 
Introduction
IntroductionIntroduction
Introductionpilavare
 
270-102-divide-and-conquer_handout.pdfCS 270Algorithm.docx
270-102-divide-and-conquer_handout.pdfCS 270Algorithm.docx270-102-divide-and-conquer_handout.pdfCS 270Algorithm.docx
270-102-divide-and-conquer_handout.pdfCS 270Algorithm.docxeugeniadean34240
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting classgiridaroori
 
Algorithm Design and Analysis
Algorithm Design and AnalysisAlgorithm Design and Analysis
Algorithm Design and AnalysisReetesh Gupta
 
Unit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdfUnit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdfAmayJaiswal4
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqPradeep Bisht
 

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)

Algorithm.ppt
Algorithm.pptAlgorithm.ppt
Algorithm.ppt
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquer
 
03 dc
03 dc03 dc
03 dc
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
Merge sort and quick sort
Merge sort and quick sortMerge sort and quick sort
Merge sort and quick sort
 
Admission in india 2015
Admission in india 2015Admission in india 2015
Admission in india 2015
 
T2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptxT2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptx
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
 
5.2 divede and conquer 03
5.2 divede and conquer 035.2 divede and conquer 03
5.2 divede and conquer 03
 
5.2 divede and conquer 03
5.2 divede and conquer 035.2 divede and conquer 03
5.2 divede and conquer 03
 
Mergesort
MergesortMergesort
Mergesort
 
Introduction
IntroductionIntroduction
Introduction
 
2.pptx
2.pptx2.pptx
2.pptx
 
270-102-divide-and-conquer_handout.pdfCS 270Algorithm.docx
270-102-divide-and-conquer_handout.pdfCS 270Algorithm.docx270-102-divide-and-conquer_handout.pdfCS 270Algorithm.docx
270-102-divide-and-conquer_handout.pdfCS 270Algorithm.docx
 
dynamic programming Rod cutting class
dynamic programming Rod cutting classdynamic programming Rod cutting class
dynamic programming Rod cutting class
 
Daa chapter 2
Daa chapter 2Daa chapter 2
Daa chapter 2
 
Algorithm Design and Analysis
Algorithm Design and AnalysisAlgorithm Design and Analysis
Algorithm Design and Analysis
 
Merge sort
Merge sortMerge sort
Merge sort
 
Unit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdfUnit-1 DAA_Notes.pdf
Unit-1 DAA_Notes.pdf
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conq
 

More from Juan Zamora, MSc. MBA (10)

Arboles Binarios
Arboles BinariosArboles Binarios
Arboles Binarios
 
Hashing
HashingHashing
Hashing
 
Arboles AVL
Arboles AVLArboles AVL
Arboles AVL
 
Quick Sort
Quick SortQuick Sort
Quick Sort
 
Heap Sort
Heap SortHeap Sort
Heap Sort
 
O(nlogn) Analisis
O(nlogn) AnalisisO(nlogn) Analisis
O(nlogn) Analisis
 
Repaso Diagramas Clase
Repaso Diagramas ClaseRepaso Diagramas Clase
Repaso Diagramas Clase
 
C1 - Insertion Sort
C1 - Insertion SortC1 - Insertion Sort
C1 - Insertion Sort
 
C1 - Conceptos OOP
C1 - Conceptos OOPC1 - Conceptos OOP
C1 - Conceptos OOP
 
Indie Game Development Intro
Indie Game Development IntroIndie Game Development Intro
Indie Game Development Intro
 

Recently uploaded

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 

Recently uploaded (20)

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 

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*