SlideShare une entreprise Scribd logo
1  sur  19
Merge Sort
Data Structures and Algorithms
Content
● What is Merge Sort?
● How it happens?
● Algorithm
● Implementation
● Complexity
● Comparison with other sort algorithms
● Advantages and Disadvantages
What is Merge Sort?
3
What is merging?
● Mixing two array elements in ascending order to
produce a third array in ascending.
Ex:
12
15
45
10
22
30
10
12
15
22
30
45
Array A Array B
Array C
» Merge sort is a sorting technique based on divide and
conquer technique with worst-case time complexity
being O(n log n)
» In computer science, merge sort is an efficient, most
respected ,general-purpose and comparison-based
sorting algorithm
» In simply, merge sort first divides the array into equal
halves and then combines them in a sorted manner
4
5
» To merge two sorted arrays,firstly we index both arrays
starting at zero,where the smallest element is located.
» Comparing the elements at each index,we choose the smaller
element,put it into the array that we are merging into.
» Increment the index of the smaller
element.
» By this method,we continually select
the next smallest element from the
two arrays and merge them into
sorted array.
How it happens?
Divide
Problem is decomposed into one or more sub problems
Conquer
Every sub problem is solved recursively
Combine
Merge the solutions of subproblems to
create the solution of the original problem
6
How it happens cont;
Ex:
Array Name : A
Starting index : p
Ending index : r
Array : A[p..r]
7
How it happens cont;
Divide
Mid point of p and r : q
the subarrays : A[p..q] and A[q+1, r]
Conquer
Sorting subarrays A[p..q] and A[q+1, r] till the base case is
reached
Combine
Combining two sorted subarrays A[p..q] and A[q+1, r]
8
9
Algorithm MergeSort(l,h){
if(l<h){
mid=(l+h)/2;
MergeSort(l,mid);
MergeSort((mid+1),h);
Merge(l,mid,h);
}
}
4 1 3 47
0 1 2 43
Low
Mid
High
l = low , h = high
2
5
6
0 1 2 3
8 5
76
9
Algorithm
10
4 1 3
4
2
5
6
0 1 2 3
8 5
76
7
0,7
0,3 4,7
0,1 2,3 4,5 6,7
0,0 1,1 2,2 3,3 4,4 5,5 6,6 7,7
Split
Merge
1 2
3
4 5
6
7
merging steps
public class MergeSortEasy {
private static void mergesort(int low, int high){
if(low < high){
int middle = (high + low) / 2;
mergesort(low, middle);
mergesort(middle + 1, high);
merge(low, middle, high);
}
}
11
Implementation
12
private static void merge(int low, int middle, int high){
for(int i = low; i <= high; i++){
helper[i] = numbers[i];
}
int i = low;
int j = middle + 1;
int k = low;
13
while(i <= middle && j <= high){
if(helper[i] <= helper[j]){
numbers[k] = helper[i];
i++;
} else {
numbers[k] = helper[j];
j++;
}
k++;
}
14
while( i <= middle){
numbers[k] = helper[i];
k++;
i++;
}
}
}
15
·Best, worst, and average time complexity of algorithm express what the
resource usage is at least, at most and on average, respectively.
·In merge Sort algorithm it can be expressed as,
T(n)=T(n/2)+T(n/2)+ ɵ(n)
T(n) = 2T(n/2) + ɵ(n)
T(n) ={2T(n/2) + cn} (if n>1)
f(n)=cn
T(n)= ɵ(nlgn)
·In all 3 cases (worst, average and best) time complexity of Merge Sort
is ɵ(nLogn).
Time Complexity
16
Space Complexity
● Space complexity of merge sort is O(n).
● In every recursive call that we create an array for
merging and they take no more than O(n)space.
● When the merging is done ,these arrays are
deleted and some new ones will be created in
some other recursive call.
17
Comparison with other sort algorithms
•Merge sort is a stable sort and is more efficient at handling slow to
access sequential media
•Merge sort is often best choice for sorting a linked list
•Heapsort has same time bounds as merge sort (heapsort requires
only O(1) and merge sort requires O(n) )
•Relatively easy to implement merge sort in such a way it requires
only O(1) extra space
•Slow random access performance of a linked list make some other
algorithms perform poor (quick sort) and some others completely
impossible (heapsort)
18
Thank You!
19

Contenu connexe

Tendances (20)

Merge sort analysis and its real time applications
Merge sort analysis and its real time applicationsMerge sort analysis and its real time applications
Merge sort analysis and its real time applications
 
Insertion sort
Insertion sort Insertion sort
Insertion sort
 
Marge Sort
Marge SortMarge Sort
Marge Sort
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Merge sort
Merge sortMerge sort
Merge sort
 
Optimal binary search tree dynamic programming
Optimal binary search tree   dynamic programmingOptimal binary search tree   dynamic programming
Optimal binary search tree dynamic programming
 
Mergesort
MergesortMergesort
Mergesort
 
3.8 quicksort
3.8 quicksort3.8 quicksort
3.8 quicksort
 
Insertion Sorting
Insertion SortingInsertion Sorting
Insertion Sorting
 
Presentation on the topic selection sort
Presentation on the topic selection sortPresentation on the topic selection sort
Presentation on the topic selection sort
 
Merge sort
Merge sortMerge sort
Merge sort
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
Bucket sort
Bucket sortBucket sort
Bucket sort
 
Binary Search
Binary SearchBinary Search
Binary Search
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
 
Bubble Sort
Bubble SortBubble Sort
Bubble Sort
 
Insertion and merge sort
Insertion and merge sortInsertion and merge sort
Insertion and merge sort
 

Similaire à Merge sort

Step 1 Implement the getSortedRunLength() methodImplement the get.pdf
Step 1 Implement the getSortedRunLength() methodImplement the get.pdfStep 1 Implement the getSortedRunLength() methodImplement the get.pdf
Step 1 Implement the getSortedRunLength() methodImplement the get.pdfaloeplusint
 
14-sorting (3).ppt
14-sorting (3).ppt14-sorting (3).ppt
14-sorting (3).pptyasser3omr
 
Lec 1 Ds
Lec 1 DsLec 1 Ds
Lec 1 DsQundeel
 
Data Structure
Data StructureData Structure
Data Structuresheraz1
 
Lec 1 Ds
Lec 1 DsLec 1 Ds
Lec 1 DsQundeel
 
Advance data structure & algorithm
Advance data structure & algorithmAdvance data structure & algorithm
Advance data structure & algorithmK Hari Shankar
 
Decimal Long Double Double Double. Represents double-precision floating-point...
Decimal Long Double Double Double. Represents double-precision floating-point...Decimal Long Double Double Double. Represents double-precision floating-point...
Decimal Long Double Double Double. Represents double-precision floating-point...Anwar Patel
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureRai University
 
Java Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfJava Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfNiravPanchal50
 
Size measurement and estimation
Size measurement and estimationSize measurement and estimation
Size measurement and estimationLouis A. Poulin
 
An Introduction to Test Driven Development with React
An Introduction to Test Driven Development with ReactAn Introduction to Test Driven Development with React
An Introduction to Test Driven Development with ReactFITC
 

Similaire à Merge sort (20)

Step 1 Implement the getSortedRunLength() methodImplement the get.pdf
Step 1 Implement the getSortedRunLength() methodImplement the get.pdfStep 1 Implement the getSortedRunLength() methodImplement the get.pdf
Step 1 Implement the getSortedRunLength() methodImplement the get.pdf
 
14-sorting.ppt
14-sorting.ppt14-sorting.ppt
14-sorting.ppt
 
14-sorting (3).ppt
14-sorting (3).ppt14-sorting (3).ppt
14-sorting (3).ppt
 
14-sorting.ppt
14-sorting.ppt14-sorting.ppt
14-sorting.ppt
 
14-sorting.ppt
14-sorting.ppt14-sorting.ppt
14-sorting.ppt
 
Lec 1 Ds
Lec 1 DsLec 1 Ds
Lec 1 Ds
 
Data Structure
Data StructureData Structure
Data Structure
 
Lec 1 Ds
Lec 1 DsLec 1 Ds
Lec 1 Ds
 
Heap, quick and merge sort
Heap, quick and merge sortHeap, quick and merge sort
Heap, quick and merge sort
 
UNIT V.docx
UNIT V.docxUNIT V.docx
UNIT V.docx
 
UNIT IV -Data Structures.pdf
UNIT IV -Data Structures.pdfUNIT IV -Data Structures.pdf
UNIT IV -Data Structures.pdf
 
Advance data structure & algorithm
Advance data structure & algorithmAdvance data structure & algorithm
Advance data structure & algorithm
 
Decimal Long Double Double Double. Represents double-precision floating-point...
Decimal Long Double Double Double. Represents double-precision floating-point...Decimal Long Double Double Double. Represents double-precision floating-point...
Decimal Long Double Double Double. Represents double-precision floating-point...
 
Sorting techniques
Sorting techniques Sorting techniques
Sorting techniques
 
Merge sort
Merge sortMerge sort
Merge sort
 
Bca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structureBca ii dfs u-1 introduction to data structure
Bca ii dfs u-1 introduction to data structure
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 
Java Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfJava Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdf
 
Size measurement and estimation
Size measurement and estimationSize measurement and estimation
Size measurement and estimation
 
An Introduction to Test Driven Development with React
An Introduction to Test Driven Development with ReactAn Introduction to Test Driven Development with React
An Introduction to Test Driven Development with React
 

Dernier

Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
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
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
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
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
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
 

Dernier (20)

Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
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
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
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
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
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
 

Merge sort

  • 1. Merge Sort Data Structures and Algorithms
  • 2. Content ● What is Merge Sort? ● How it happens? ● Algorithm ● Implementation ● Complexity ● Comparison with other sort algorithms ● Advantages and Disadvantages
  • 3. What is Merge Sort? 3 What is merging? ● Mixing two array elements in ascending order to produce a third array in ascending. Ex: 12 15 45 10 22 30 10 12 15 22 30 45 Array A Array B Array C
  • 4. » Merge sort is a sorting technique based on divide and conquer technique with worst-case time complexity being O(n log n) » In computer science, merge sort is an efficient, most respected ,general-purpose and comparison-based sorting algorithm » In simply, merge sort first divides the array into equal halves and then combines them in a sorted manner 4
  • 5. 5 » To merge two sorted arrays,firstly we index both arrays starting at zero,where the smallest element is located. » Comparing the elements at each index,we choose the smaller element,put it into the array that we are merging into. » Increment the index of the smaller element. » By this method,we continually select the next smallest element from the two arrays and merge them into sorted array.
  • 6. How it happens? Divide Problem is decomposed into one or more sub problems Conquer Every sub problem is solved recursively Combine Merge the solutions of subproblems to create the solution of the original problem 6
  • 7. How it happens cont; Ex: Array Name : A Starting index : p Ending index : r Array : A[p..r] 7
  • 8. How it happens cont; Divide Mid point of p and r : q the subarrays : A[p..q] and A[q+1, r] Conquer Sorting subarrays A[p..q] and A[q+1, r] till the base case is reached Combine Combining two sorted subarrays A[p..q] and A[q+1, r] 8
  • 9. 9 Algorithm MergeSort(l,h){ if(l<h){ mid=(l+h)/2; MergeSort(l,mid); MergeSort((mid+1),h); Merge(l,mid,h); } } 4 1 3 47 0 1 2 43 Low Mid High l = low , h = high 2 5 6 0 1 2 3 8 5 76 9 Algorithm
  • 10. 10 4 1 3 4 2 5 6 0 1 2 3 8 5 76 7 0,7 0,3 4,7 0,1 2,3 4,5 6,7 0,0 1,1 2,2 3,3 4,4 5,5 6,6 7,7 Split Merge 1 2 3 4 5 6 7 merging steps
  • 11. public class MergeSortEasy { private static void mergesort(int low, int high){ if(low < high){ int middle = (high + low) / 2; mergesort(low, middle); mergesort(middle + 1, high); merge(low, middle, high); } } 11 Implementation
  • 12. 12 private static void merge(int low, int middle, int high){ for(int i = low; i <= high; i++){ helper[i] = numbers[i]; } int i = low; int j = middle + 1; int k = low;
  • 13. 13 while(i <= middle && j <= high){ if(helper[i] <= helper[j]){ numbers[k] = helper[i]; i++; } else { numbers[k] = helper[j]; j++; } k++; }
  • 14. 14 while( i <= middle){ numbers[k] = helper[i]; k++; i++; } } }
  • 15. 15
  • 16. ·Best, worst, and average time complexity of algorithm express what the resource usage is at least, at most and on average, respectively. ·In merge Sort algorithm it can be expressed as, T(n)=T(n/2)+T(n/2)+ ɵ(n) T(n) = 2T(n/2) + ɵ(n) T(n) ={2T(n/2) + cn} (if n>1) f(n)=cn T(n)= ɵ(nlgn) ·In all 3 cases (worst, average and best) time complexity of Merge Sort is ɵ(nLogn). Time Complexity 16
  • 17. Space Complexity ● Space complexity of merge sort is O(n). ● In every recursive call that we create an array for merging and they take no more than O(n)space. ● When the merging is done ,these arrays are deleted and some new ones will be created in some other recursive call. 17
  • 18. Comparison with other sort algorithms •Merge sort is a stable sort and is more efficient at handling slow to access sequential media •Merge sort is often best choice for sorting a linked list •Heapsort has same time bounds as merge sort (heapsort requires only O(1) and merge sort requires O(n) ) •Relatively easy to implement merge sort in such a way it requires only O(1) extra space •Slow random access performance of a linked list make some other algorithms perform poor (quick sort) and some others completely impossible (heapsort) 18

Notes de l'éditeur

  1. *Divide and conquer *Recurrion is taken significant place *what is recursion
  2. * Adding values on temporary on a data structure
  3. *Choose the smallest and highest value *0th and 1th
  4. *shift the values