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

Estructura de Datos Unidad - V: Métodos de Ordenamiento
Estructura de Datos Unidad - V: Métodos de OrdenamientoEstructura de Datos Unidad - V: Métodos de Ordenamiento
Estructura de Datos Unidad - V: Métodos de OrdenamientoJosé Antonio Sandoval Acosta
 
Recursividad (Divide y Vencerás)
Recursividad (Divide y Vencerás)Recursividad (Divide y Vencerás)
Recursividad (Divide y Vencerás)Lester Sanchez
 
Exposición
ExposiciónExposición
Exposicióntorruxi
 
Algebra Relacional
Algebra RelacionalAlgebra Relacional
Algebra RelacionalBlanca Parra
 
ORDENAMIENTO POR INTERCAMBIO
ORDENAMIENTO POR INTERCAMBIOORDENAMIENTO POR INTERCAMBIO
ORDENAMIENTO POR INTERCAMBIOWilmer Quintero
 
Insertion sort
Insertion sortInsertion sort
Insertion sortMichael
 
Operaciones entre lenguajes
Operaciones entre lenguajesOperaciones entre lenguajes
Operaciones entre lenguajesJean Bernard
 

What's hot (9)

Estructura de Datos Unidad - V: Métodos de Ordenamiento
Estructura de Datos Unidad - V: Métodos de OrdenamientoEstructura de Datos Unidad - V: Métodos de Ordenamiento
Estructura de Datos Unidad - V: Métodos de Ordenamiento
 
Recursividad (Divide y Vencerás)
Recursividad (Divide y Vencerás)Recursividad (Divide y Vencerás)
Recursividad (Divide y Vencerás)
 
Exposición
ExposiciónExposición
Exposición
 
Algebra Relacional
Algebra RelacionalAlgebra Relacional
Algebra Relacional
 
Metodos de ordenamiento
Metodos de ordenamientoMetodos de ordenamiento
Metodos de ordenamiento
 
Recursividad
RecursividadRecursividad
Recursividad
 
ORDENAMIENTO POR INTERCAMBIO
ORDENAMIENTO POR INTERCAMBIOORDENAMIENTO POR INTERCAMBIO
ORDENAMIENTO POR INTERCAMBIO
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Operaciones entre lenguajes
Operaciones entre lenguajesOperaciones entre lenguajes
Operaciones entre lenguajes
 

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 (11)

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
 
Notacion Asintotica
Notacion AsintoticaNotacion Asintotica
Notacion Asintotica
 
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

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
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
 
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
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 

Recently uploaded (20)

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
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
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
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...
 
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
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 

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*