SlideShare a Scribd company logo
1 of 23
Merge Sort and Quick Sort
CSC 391
2
Sorting
• Insertion sort
– Design approach:
– Sorts in place:
– Best case:
– Worst case:
• Bubble Sort
– Design approach:
– Sorts in place:
– Running time:
Yes
(n)
(n2)
incremental
Yes
(n2)
incremental
3
Sorting
• Selection sort
– Design approach:
– Sorts in place:
– Running time:
• Merge Sort
– Design approach:
– Sorts in place:
– Running time:
Yes
(n2)
incremental
No
Let’s see!!
divide and conquer
4
Divide-and-Conquer
• Divide the problem into a number of sub-problems
– Similar sub-problems of smaller size
• Conquer the sub-problems
– Solve the sub-problems recursively
– Sub-problem size small enough  solve the problems in
straightforward manner
• Combine the solutions of the sub-problems
– Obtain the solution for the original problem
5
Merge Sort Approach
• To sort an array A[p . . r]:
• Divide
– Divide the n-element sequence to be sorted into two
subsequences of n/2 elements each
• Conquer
– Sort the subsequences recursively using merge sort
– When the size of the sequences is 1 there is nothing
more to do
• Combine
– Merge the two sorted subsequences
6
Merge Sort
Alg.: MERGE-SORT(A, p, r)
if p < r Check for base case
then q ← (p + r)/2 Divide
MERGE-SORT(A, p, q) Conquer
MERGE-SORT(A, q + 1, r) Conquer
MERGE(A, p, q, r) Combine
• Initial call: MERGE-SORT(A, 1, n)
1 2 3 4 5 6 7 8
62317425
p rq
7
Example – n Power of 2
1 2 3 4 5 6 7 8
q = 462317425
1 2 3 4
7425
5 6 7 8
6231
1 2
25
3 4
74
5 6
31
7 8
62
1
5
2
2
3
4
4
7 1
6
3
7
2
8
6
5
Divide
8
Example – n Power of 2
1
5
2
2
3
4
4
7 1
6
3
7
2
8
6
5
1 2 3 4 5 6 7 8
76543221
1 2 3 4
7542
5 6 7 8
6321
1 2
52
3 4
74
5 6
31
7 8
62
Conquer
and
Merge
9
Example – n Not a Power of 2
62537416274
1 2 3 4 5 6 7 8 9 10 11
q = 6
416274
1 2 3 4 5 6
62537
7 8 9 10 11
q = 9q = 3
274
1 2 3
416
4 5 6
537
7 8 9
62
10 11
74
1 2
2
3
16
4 5
4
6
37
7 8
5
9
2
10
6
11
4
1
7
2
6
4
1
5
7
7
3
8
Divide
10
Example – n Not a Power of 2
77665443221
1 2 3 4 5 6 7 8 9 10 11
764421
1 2 3 4 5 6
76532
7 8 9 10 11
742
1 2 3
641
4 5 6
753
7 8 9
62
10 11
2
3
4
6
5
9
2
10
6
11
4
1
7
2
6
4
1
5
7
7
3
8
74
1 2
61
4 5
73
7 8
Conquer
and
Merge
11
Merge - Pseudocode
Alg.: MERGE(A, p, q, r)
1. Compute n1 and n2
2. Copy the first n1 elements into L[1
. . n1 + 1] and the next n2 elements into R[1 . . n2 + 1]
3. L[n1 + 1] ← ; R[n2 + 1] ← 
4. i ← 1; j ← 1
5. for k ← p to r
6. do if L[ i ] ≤ R[ j ]
7. then A[k] ← L[ i ]
8. i ←i + 1
9. else A[k] ← R[ j ]
10. j ← j + 1
p q
7542
6321
rq + 1
L
R


1 2 3 4 5 6 7 8
63217542
p rq
n1 n2
Algorithm:
mergesort( int [] a, int left, int right)
{
if (right > left)
{ middle = left + (right - left)/2;
mergesort(a, left, middle);
mergesort(a, middle+1, right);
merge(a, left, middle, right); }
}
Assumption: N is a power of two. For N = 1: time is a constant (denoted by 1)
Otherwise, time to mergesort N elements = time to mergesort N/2 elements + time to merge
two arrays each N/2 elements.
Time to merge two arrays each N/2 elements is linear, i.e. N
Thus we have:
(1) T(1) = 1
(2) T(N) = 2T(N/2) + N
Next we will solve this recurrence relation. First we divide (2) by N:
(3) T(N) / N = T(N/2) / (N/2) + 1
Complexity of Merge Sort
N is a power of two, so we can write
(4) T(N/2) / (N/2) = T(N/4) / (N/4) +1
(5) T(N/4) / (N/4) = T(N/8) / (N/8) +1
(6) T(N/8) / (N/8) = T(N/16) / (N/16) +1
(7) ……
(8) T(2) / 2 = T(1) / 1 + 1
Now we add equations (3) through (8) : the sum of their left-hand sides will be equal to
the sum of their right-hand sides:
T(N) / N + T(N/2) / (N/2) + T(N/4) / (N/4) + … + T(2)/2 =
T(N/2) / (N/2) + T(N/4) / (N/4) + ….+ T(2) / 2 + T(1) / 1 + LogN
(LogN is the sum of 1s in the right-hand sides)
After crossing the equal term, we get
(9) T(N)/N = T(1)/1 + LogN
T(1) is 1, hence we obtain
(10) T(N) = N + NlogN = O(NlogN)
Hence the complexity of the MergeSort algorithm is O(NlogN).
Complexity of Merge Sort
14
Quicksort
• Sort an array A[p…r]
• Divide
– Partition the array A into 2 subarrays A[p..q] and A[q+1..r], such that
each element of A[p..q] is smaller than or equal to each element in
A[q+1..r]
– Need to find index q to partition the array
≤A[p…q] A[q+1…r]
15
Quicksort
• Conquer
– Recursively sort A[p..q] and A[q+1..r] using Quicksort
• Combine
– Trivial: the arrays are sorted in place
– No additional work is required to combine them
– The entire array is now sorted
A[p…q] A[q+1…r]≤
16
Recurrence
Alg.: QUICKSORT(A, p, r)
if p < r
then q  PARTITION(A, p, r)
QUICKSORT (A, p, q)
QUICKSORT (A, q+1, r)
Recurrence:
Initially: p=1, r=n
T(n) = T(q) + T(n – q) + n
17
Partitioning the Array
Alg. PARTITION (A, p, r)
1. x  A[p]
2. i  p – 1
3. j  r + 1
4. while TRUE
5. do repeat j  j – 1
6. until A[j] ≤ x
7. do repeat i  i + 1
8. until A[i] ≥ x
9. if i < j
10. then exchange A[i]  A[j]
11. else return j
Running time: (n)
n = r – p + 1
73146235
i j
A:
arap
ij=q
A:
A[p…q] A[q+1…r]≤
p r
Each element is
visited once!
Partition can be done in O(n) time, where n is the size of
the array. Let T(n) be the number of comparisons
required by Quicksort.
If the pivot ends up at position k, then we have
To determine best-, worst-, and average-case complexity
we need to determine the values of k that correspond
to these cases.
Analysis of quicksort
T(n) T(nk)  T(k 1)  n
Best-Case Complexity
The best case is clearly when the pivot always
partitions the array equally.
Intuitively, this would lead to a recursive depth of at
most lg n calls
We can actually prove this. In this case
– T(n) T(n/2)  T(n/2)  n  (n lg n)
Best Case Partitioning
• Best-case partitioning
– Partitioning produces two regions of size n/2
• Recurrence: q=n/2
T(n) = 2T(n/2) + (n)
T(n) = (nlgn) (Master theorem)
Average-Case Complexity
Average case is rather complex, but is where the
algorithm earns its name. The bottom line is: T(n) =
(nlgn)
Worst Case Partitioning
The worst-case behavior for quicksort occurs when the
partitioning routine produces one region with n - 1 elements and
one with only l element.
Let us assume that this
Unbalanced partitioning arises
at every step of the algorithm.
Since partitioning costs (n) time
and T(1) = (1), the recurrence for
the running time is
T(n) = T(n - 1) + (n).
To evaluate this recurrence, we observe that T(1) = (1) and then
iterate:
n
n - 1
n - 2
n - 3
2
1
1
1
1
1
1
n
n
n
n - 1
n - 2
3
2
(n2)
Best case: split in the middle — Θ( n log n)
Worst case: sorted array! — Θ( n2)
Average case: random arrays — Θ( n log n)
Worst Case Partitioning

More Related Content

What's hot

Algorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms IAlgorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms IMohamed Loey
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sortMadhu Bala
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingEduardo Bergavera
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSGokul Hari
 
Design & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture NotesDesign & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture NotesFellowBuddy.com
 
Topological Sorting
Topological SortingTopological Sorting
Topological SortingShahDhruv21
 
Optimal binary search tree
Optimal binary search treeOptimal binary search tree
Optimal binary search treeKavya P
 
Quick sort algorithn
Quick sort algorithnQuick sort algorithn
Quick sort algorithnKumar
 
Algorithms Lecture 5: Sorting Algorithms II
Algorithms Lecture 5: Sorting Algorithms IIAlgorithms Lecture 5: Sorting Algorithms II
Algorithms Lecture 5: Sorting Algorithms IIMohamed Loey
 
Asymptotic Notations
Asymptotic NotationsAsymptotic Notations
Asymptotic NotationsRishabh Soni
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data StructureDharita Chokshi
 
Stressen's matrix multiplication
Stressen's matrix multiplicationStressen's matrix multiplication
Stressen's matrix multiplicationKumar
 

What's hot (20)

Merge sort algorithm power point presentation
Merge sort algorithm power point presentationMerge sort algorithm power point presentation
Merge sort algorithm power point presentation
 
Algorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms IAlgorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms I
 
Quick Sort
Quick SortQuick Sort
Quick Sort
 
Divide and conquer - Quick sort
Divide and conquer - Quick sortDivide and conquer - Quick sort
Divide and conquer - Quick sort
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Ppt bubble sort
Ppt bubble sortPpt bubble sort
Ppt bubble sort
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMS
 
Design & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture NotesDesign & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture Notes
 
Heap and heapsort
Heap and heapsortHeap and heapsort
Heap and heapsort
 
Topological Sorting
Topological SortingTopological Sorting
Topological Sorting
 
Optimal binary search tree
Optimal binary search treeOptimal binary search tree
Optimal binary search tree
 
Quick sort algorithn
Quick sort algorithnQuick sort algorithn
Quick sort algorithn
 
Algorithms Lecture 5: Sorting Algorithms II
Algorithms Lecture 5: Sorting Algorithms IIAlgorithms Lecture 5: Sorting Algorithms II
Algorithms Lecture 5: Sorting Algorithms II
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Asymptotic Notations
Asymptotic NotationsAsymptotic Notations
Asymptotic Notations
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Stressen's matrix multiplication
Stressen's matrix multiplicationStressen's matrix multiplication
Stressen's matrix multiplication
 
Selection sorting
Selection sortingSelection sorting
Selection sorting
 

Viewers also liked

Viewers also liked (11)

358 33 powerpoint-slides_14-sorting_chapter-14
358 33 powerpoint-slides_14-sorting_chapter-14358 33 powerpoint-slides_14-sorting_chapter-14
358 33 powerpoint-slides_14-sorting_chapter-14
 
Sorting
SortingSorting
Sorting
 
Lecture 07 Data Structures - Basic Sorting
Lecture 07 Data Structures - Basic SortingLecture 07 Data Structures - Basic Sorting
Lecture 07 Data Structures - Basic Sorting
 
Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)
 
Sorting
SortingSorting
Sorting
 
Data Structures & Algorithm design using C
Data Structures & Algorithm design using C Data Structures & Algorithm design using C
Data Structures & Algorithm design using C
 
Sorting
SortingSorting
Sorting
 
Data Structure: Algorithm and analysis
Data Structure: Algorithm and analysisData Structure: Algorithm and analysis
Data Structure: Algorithm and analysis
 
Complexity of Algorithm
Complexity of AlgorithmComplexity of Algorithm
Complexity of Algorithm
 
Time and space complexity
Time and space complexityTime and space complexity
Time and space complexity
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 

Similar to Merge sort and quick sort

presentation_mergesortquicksort_1458716068_193111.ppt
presentation_mergesortquicksort_1458716068_193111.pptpresentation_mergesortquicksort_1458716068_193111.ppt
presentation_mergesortquicksort_1458716068_193111.pptajiths82
 
MergesortQuickSort.ppt
MergesortQuickSort.pptMergesortQuickSort.ppt
MergesortQuickSort.pptAliAhmad38278
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquerVikas Sharma
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquerKrish_ver2
 
T2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptxT2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptxGadaFarhan
 
Quicksort analysis
Quicksort analysisQuicksort analysis
Quicksort analysisPremjeet Roy
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingzukun
 
Data Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge SortData Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge SortManishPrajapati78
 
Introduction
IntroductionIntroduction
Introductionpilavare
 
Admission in india 2015
Admission in india 2015Admission in india 2015
Admission in india 2015Edhole.com
 
Skiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortSkiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortzukun
 
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
 
Algorithim lec1.pptx
Algorithim lec1.pptxAlgorithim lec1.pptx
Algorithim lec1.pptxrediet43
 
Quick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisQuick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisSNJ Chaudhary
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquerchidabdu
 

Similar to Merge sort and quick sort (20)

Merge Sort
Merge SortMerge Sort
Merge Sort
 
presentation_mergesortquicksort_1458716068_193111.ppt
presentation_mergesortquicksort_1458716068_193111.pptpresentation_mergesortquicksort_1458716068_193111.ppt
presentation_mergesortquicksort_1458716068_193111.ppt
 
MergesortQuickSort.ppt
MergesortQuickSort.pptMergesortQuickSort.ppt
MergesortQuickSort.ppt
 
Divide and conquer
Divide and conquerDivide and conquer
Divide and conquer
 
03 dc
03 dc03 dc
03 dc
 
5.2 divide and conquer
5.2 divide and conquer5.2 divide and conquer
5.2 divide and conquer
 
T2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptxT2311 - Ch 4_Part1.pptx
T2311 - Ch 4_Part1.pptx
 
Quicksort analysis
Quicksort analysisQuicksort analysis
Quicksort analysis
 
Skiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sortingSkiena algorithm 2007 lecture09 linear sorting
Skiena algorithm 2007 lecture09 linear sorting
 
Data Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge SortData Structure and Algorithms Merge Sort
Data Structure and Algorithms Merge Sort
 
Introduction
IntroductionIntroduction
Introduction
 
Admission in india 2015
Admission in india 2015Admission in india 2015
Admission in india 2015
 
Algorithm.ppt
Algorithm.pptAlgorithm.ppt
Algorithm.ppt
 
Skiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksortSkiena algorithm 2007 lecture08 quicksort
Skiena algorithm 2007 lecture08 quicksort
 
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
 
Algorithim lec1.pptx
Algorithim lec1.pptxAlgorithim lec1.pptx
Algorithim lec1.pptx
 
quick and merge.pptx
quick and merge.pptxquick and merge.pptx
quick and merge.pptx
 
Quick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisQuick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And Analysis
 
Sienna 4 divideandconquer
Sienna 4 divideandconquerSienna 4 divideandconquer
Sienna 4 divideandconquer
 

More from Shakila Mahjabin (15)

Computer processing
Computer processingComputer processing
Computer processing
 
Arrays in CPP
Arrays in CPPArrays in CPP
Arrays in CPP
 
CSC 433 Sample normalization SQL Question
CSC 433 Sample normalization SQL QuestionCSC 433 Sample normalization SQL Question
CSC 433 Sample normalization SQL Question
 
SQL : introduction
SQL : introductionSQL : introduction
SQL : introduction
 
Normalization
NormalizationNormalization
Normalization
 
Solution of Erds
Solution of ErdsSolution of Erds
Solution of Erds
 
Entity Relationship Diagram
Entity Relationship DiagramEntity Relationship Diagram
Entity Relationship Diagram
 
Ch1- Introduction to dbms
Ch1- Introduction to dbmsCh1- Introduction to dbms
Ch1- Introduction to dbms
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Algo analysis
Algo analysisAlgo analysis
Algo analysis
 
Codes on structures
Codes on structuresCodes on structures
Codes on structures
 
Arrays
ArraysArrays
Arrays
 
array, function, pointer, pattern matching
array, function, pointer, pattern matchingarray, function, pointer, pattern matching
array, function, pointer, pattern matching
 
String operation
String operationString operation
String operation
 
Data Structure Basics
Data Structure BasicsData Structure Basics
Data Structure Basics
 

Recently uploaded

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111GangaMaiya1
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningMarc Dusseiller Dusjagr
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Celine George
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of PlayPooky Knightsmith
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfstareducators107
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxakanksha16arora
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 

Recently uploaded (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 

Merge sort and quick sort

  • 1. Merge Sort and Quick Sort CSC 391
  • 2. 2 Sorting • Insertion sort – Design approach: – Sorts in place: – Best case: – Worst case: • Bubble Sort – Design approach: – Sorts in place: – Running time: Yes (n) (n2) incremental Yes (n2) incremental
  • 3. 3 Sorting • Selection sort – Design approach: – Sorts in place: – Running time: • Merge Sort – Design approach: – Sorts in place: – Running time: Yes (n2) incremental No Let’s see!! divide and conquer
  • 4. 4 Divide-and-Conquer • Divide the problem into a number of sub-problems – Similar sub-problems of smaller size • Conquer the sub-problems – Solve the sub-problems recursively – Sub-problem size small enough  solve the problems in straightforward manner • Combine the solutions of the sub-problems – Obtain the solution for the original problem
  • 5. 5 Merge Sort Approach • To sort an array A[p . . r]: • Divide – Divide the n-element sequence to be sorted into two subsequences of n/2 elements each • Conquer – Sort the subsequences recursively using merge sort – When the size of the sequences is 1 there is nothing more to do • Combine – Merge the two sorted subsequences
  • 6. 6 Merge Sort Alg.: MERGE-SORT(A, p, r) if p < r Check for base case then q ← (p + r)/2 Divide MERGE-SORT(A, p, q) Conquer MERGE-SORT(A, q + 1, r) Conquer MERGE(A, p, q, r) Combine • Initial call: MERGE-SORT(A, 1, n) 1 2 3 4 5 6 7 8 62317425 p rq
  • 7. 7 Example – n Power of 2 1 2 3 4 5 6 7 8 q = 462317425 1 2 3 4 7425 5 6 7 8 6231 1 2 25 3 4 74 5 6 31 7 8 62 1 5 2 2 3 4 4 7 1 6 3 7 2 8 6 5 Divide
  • 8. 8 Example – n Power of 2 1 5 2 2 3 4 4 7 1 6 3 7 2 8 6 5 1 2 3 4 5 6 7 8 76543221 1 2 3 4 7542 5 6 7 8 6321 1 2 52 3 4 74 5 6 31 7 8 62 Conquer and Merge
  • 9. 9 Example – n Not a Power of 2 62537416274 1 2 3 4 5 6 7 8 9 10 11 q = 6 416274 1 2 3 4 5 6 62537 7 8 9 10 11 q = 9q = 3 274 1 2 3 416 4 5 6 537 7 8 9 62 10 11 74 1 2 2 3 16 4 5 4 6 37 7 8 5 9 2 10 6 11 4 1 7 2 6 4 1 5 7 7 3 8 Divide
  • 10. 10 Example – n Not a Power of 2 77665443221 1 2 3 4 5 6 7 8 9 10 11 764421 1 2 3 4 5 6 76532 7 8 9 10 11 742 1 2 3 641 4 5 6 753 7 8 9 62 10 11 2 3 4 6 5 9 2 10 6 11 4 1 7 2 6 4 1 5 7 7 3 8 74 1 2 61 4 5 73 7 8 Conquer and Merge
  • 11. 11 Merge - Pseudocode Alg.: MERGE(A, p, q, r) 1. Compute n1 and n2 2. Copy the first n1 elements into L[1 . . n1 + 1] and the next n2 elements into R[1 . . n2 + 1] 3. L[n1 + 1] ← ; R[n2 + 1] ←  4. i ← 1; j ← 1 5. for k ← p to r 6. do if L[ i ] ≤ R[ j ] 7. then A[k] ← L[ i ] 8. i ←i + 1 9. else A[k] ← R[ j ] 10. j ← j + 1 p q 7542 6321 rq + 1 L R   1 2 3 4 5 6 7 8 63217542 p rq n1 n2
  • 12. Algorithm: mergesort( int [] a, int left, int right) { if (right > left) { middle = left + (right - left)/2; mergesort(a, left, middle); mergesort(a, middle+1, right); merge(a, left, middle, right); } } Assumption: N is a power of two. For N = 1: time is a constant (denoted by 1) Otherwise, time to mergesort N elements = time to mergesort N/2 elements + time to merge two arrays each N/2 elements. Time to merge two arrays each N/2 elements is linear, i.e. N Thus we have: (1) T(1) = 1 (2) T(N) = 2T(N/2) + N Next we will solve this recurrence relation. First we divide (2) by N: (3) T(N) / N = T(N/2) / (N/2) + 1 Complexity of Merge Sort
  • 13. N is a power of two, so we can write (4) T(N/2) / (N/2) = T(N/4) / (N/4) +1 (5) T(N/4) / (N/4) = T(N/8) / (N/8) +1 (6) T(N/8) / (N/8) = T(N/16) / (N/16) +1 (7) …… (8) T(2) / 2 = T(1) / 1 + 1 Now we add equations (3) through (8) : the sum of their left-hand sides will be equal to the sum of their right-hand sides: T(N) / N + T(N/2) / (N/2) + T(N/4) / (N/4) + … + T(2)/2 = T(N/2) / (N/2) + T(N/4) / (N/4) + ….+ T(2) / 2 + T(1) / 1 + LogN (LogN is the sum of 1s in the right-hand sides) After crossing the equal term, we get (9) T(N)/N = T(1)/1 + LogN T(1) is 1, hence we obtain (10) T(N) = N + NlogN = O(NlogN) Hence the complexity of the MergeSort algorithm is O(NlogN). Complexity of Merge Sort
  • 14. 14 Quicksort • Sort an array A[p…r] • Divide – Partition the array A into 2 subarrays A[p..q] and A[q+1..r], such that each element of A[p..q] is smaller than or equal to each element in A[q+1..r] – Need to find index q to partition the array ≤A[p…q] A[q+1…r]
  • 15. 15 Quicksort • Conquer – Recursively sort A[p..q] and A[q+1..r] using Quicksort • Combine – Trivial: the arrays are sorted in place – No additional work is required to combine them – The entire array is now sorted A[p…q] A[q+1…r]≤
  • 16. 16 Recurrence Alg.: QUICKSORT(A, p, r) if p < r then q  PARTITION(A, p, r) QUICKSORT (A, p, q) QUICKSORT (A, q+1, r) Recurrence: Initially: p=1, r=n T(n) = T(q) + T(n – q) + n
  • 17. 17 Partitioning the Array Alg. PARTITION (A, p, r) 1. x  A[p] 2. i  p – 1 3. j  r + 1 4. while TRUE 5. do repeat j  j – 1 6. until A[j] ≤ x 7. do repeat i  i + 1 8. until A[i] ≥ x 9. if i < j 10. then exchange A[i]  A[j] 11. else return j Running time: (n) n = r – p + 1 73146235 i j A: arap ij=q A: A[p…q] A[q+1…r]≤ p r Each element is visited once!
  • 18. Partition can be done in O(n) time, where n is the size of the array. Let T(n) be the number of comparisons required by Quicksort. If the pivot ends up at position k, then we have To determine best-, worst-, and average-case complexity we need to determine the values of k that correspond to these cases. Analysis of quicksort T(n) T(nk)  T(k 1)  n
  • 19. Best-Case Complexity The best case is clearly when the pivot always partitions the array equally. Intuitively, this would lead to a recursive depth of at most lg n calls We can actually prove this. In this case – T(n) T(n/2)  T(n/2)  n  (n lg n)
  • 20. Best Case Partitioning • Best-case partitioning – Partitioning produces two regions of size n/2 • Recurrence: q=n/2 T(n) = 2T(n/2) + (n) T(n) = (nlgn) (Master theorem)
  • 21. Average-Case Complexity Average case is rather complex, but is where the algorithm earns its name. The bottom line is: T(n) = (nlgn)
  • 22. Worst Case Partitioning The worst-case behavior for quicksort occurs when the partitioning routine produces one region with n - 1 elements and one with only l element. Let us assume that this Unbalanced partitioning arises at every step of the algorithm. Since partitioning costs (n) time and T(1) = (1), the recurrence for the running time is T(n) = T(n - 1) + (n). To evaluate this recurrence, we observe that T(1) = (1) and then iterate: n n - 1 n - 2 n - 3 2 1 1 1 1 1 1 n n n n - 1 n - 2 3 2 (n2)
  • 23. Best case: split in the middle — Θ( n log n) Worst case: sorted array! — Θ( n2) Average case: random arrays — Θ( n log n) Worst Case Partitioning