SlideShare une entreprise Scribd logo
1  sur  21
Algorithms
Merge Sort
Abdelrahman M. Saleh
List of contents
● Introduction
● Example w/ illustrating figures
● Algorithm
● implementation (Java, C++, Python)
● Performance Runtime
○ Best, Average and worst cases.
● Execution
● Other Notes
Introduction
● Divide and Conquer algorithm. It divides input array in two halves, calls itself for the
two halves and then merges the two sorted halves.
● The merge() function is used for merging two halves The merge(a, l, m, r) is key process
that assumes that a[l..m] and a[m+1..r] are sorted and merges the two sorted sub-arrays
into one .
Example
Source : Wikebedia
Algorithm .
➔ Array name “arr” , left-most element “l”, right-most element “r”
● If r is bigger than l
○ Find the middle point to divide the array into two halves :
■ middle m = (l+r)/2
○ Call mergeSort for first half :
■ Call mergeSort(arr, l, m)
○ Call mergeSort for second half :
■ Call mergeSort(arr, m+1, r)
○ Merge the two halves sorted in step 2 and 3 :
■ Call merge(arr, l, m, r)
Implementation .
C++
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
//Same as (l+r)/2, but avoids overflow for large l and r .
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
C++
Continue ...
void merge(int arr[], int l, int m, int r)
{
int i = 0, j = 0, k = 1 ;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2]; /* create temp arrays */
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
// Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
C++
Continue ...
/* Merge the temp arrays back into arr[l..r]*/
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i]; i++;
}
else
{
arr[k] = R[j]; j++;
}
k++;
}
// Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
C++
Continue ...
/* Copy the remaining elements of L[], if there are any */
while (i < n1)
{
arr[k] = L[i]; i++; k++;
}
/* Copy the remaining elements of R[], if there are any */
while (j < n2)
{
arr[k] = R[j]; j++; k++;
}
}
// Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
JAVA
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr , m+1, r);
merge(arr, l, m, r);
}
}
JAVA
Continue ...
/* Merge the temp arrays back into arr[l..r]*/
void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1]; /* Create temp arrays */
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
// Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
JAVA
Continue ...
int i = 0, j = 0, int k = l ; // Initial indexes of first, second and merged subarrays relatively .
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i]; i++;
}else{
arr[k] = R[j]; j++;
}
k++;
}
// Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
JAVA
Continue ...
/* Copy the remaining elements of L[], if there are any */
while (i < n1)
{
arr[k] = L[i]; i++; k++;
}
/* Copy the remaining elements of R[], if there are any */
while (j < n2)
{
arr[k] = R[j]; j++; k++;
}
}
// Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
Python .
def mergeSort(arr, l, r):
if l < r :
m = (l+(r-1))/2 #Same as (l+r)/2, but avoids overflow for large l and r
#Sort first and second halves
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
Python
Continue ...
def merge(arr, l, m, r):
n1 = m - l - 1
n2 = r - m
L = [0] * (n1) #create temp arrays
R = [0] * (n2)
#copy data to temp arrays
for i in range (0, n1):
L[i] = arr(l + i)
for j in range (0, n2):
R[j] = arr(m + 1 + j)
// Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
Python
Continue ...
i = 0
j = 0
k = l
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[i]
j += 1
// Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
Python .
#Copy the remaining elements of L[], if there are any
while i < n1:
arr[k] = L[i]
i += 1
k += 11
#Copy the remaining elements of R[], if there are any
while j < n2:
arr[k] = R[j]
j += 1
k += 1
// Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
Performance Runtime
● Time complexity Θ(nlog(n)) .
● In merge sort Best, Average and Worst cases are the same “Θ(nlog(n))” as it always
divides the array in two halves and take linear time to merge two halves.
Execution .
Input array : [4, 6, 3, 2, 1, 9, 7]
Output Array: [1, 2, 3, 4, 6, 7, 9]
Other Notes .
● Algorithmic Paradigm: Divide Approach
● Sorting In Place: No
● Stable: Yes
● Online: Yes

Contenu connexe

Tendances

Different Sorting tecniques in Data Structure
Different Sorting tecniques in Data StructureDifferent Sorting tecniques in Data Structure
Different Sorting tecniques in Data StructureTushar Gonawala
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-SortTareq Hasan
 
Stacks in DATA STRUCTURE
Stacks in DATA STRUCTUREStacks in DATA STRUCTURE
Stacks in DATA STRUCTUREMandeep Singh
 
Data Structures and Algorithm Analysis
Data Structures  and  Algorithm AnalysisData Structures  and  Algorithm Analysis
Data Structures and Algorithm AnalysisMary Margarat
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1Amrinder Arora
 
Stack & Queue using Linked List in Data Structure
Stack & Queue using Linked List in Data StructureStack & Queue using Linked List in Data Structure
Stack & Queue using Linked List in Data StructureMeghaj Mallick
 
Quick sort-Data Structure
Quick sort-Data StructureQuick sort-Data Structure
Quick sort-Data StructureJeanie Arnoco
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sortingKaushal Shah
 
Selection sort
Selection sortSelection sort
Selection sortJay Patel
 
SINGLE SOURCE SHORTEST PATH.ppt
SINGLE SOURCE SHORTEST PATH.pptSINGLE SOURCE SHORTEST PATH.ppt
SINGLE SOURCE SHORTEST PATH.pptshanthishyam
 
자료구조 2014-2018년 출석수업대체시험 기출문제
자료구조 2014-2018년 출석수업대체시험 기출문제자료구조 2014-2018년 출석수업대체시험 기출문제
자료구조 2014-2018년 출석수업대체시험 기출문제Lee Sang-Ho
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programmingKrish_ver2
 
Linear Search & Binary Search
Linear Search & Binary SearchLinear Search & Binary Search
Linear Search & Binary SearchReem Alattas
 
자료구조 2014-2018년 기말시험 기출문제
자료구조 2014-2018년 기말시험 기출문제자료구조 2014-2018년 기말시험 기출문제
자료구조 2014-2018년 기말시험 기출문제Lee Sang-Ho
 

Tendances (20)

Different Sorting tecniques in Data Structure
Different Sorting tecniques in Data StructureDifferent Sorting tecniques in Data Structure
Different Sorting tecniques in Data Structure
 
Algorithm: Quick-Sort
Algorithm: Quick-SortAlgorithm: Quick-Sort
Algorithm: Quick-Sort
 
Marge Sort
Marge SortMarge Sort
Marge Sort
 
Cursors in MySQL
Cursors in MySQL Cursors in MySQL
Cursors in MySQL
 
Quick sort
Quick sortQuick sort
Quick sort
 
Stacks in DATA STRUCTURE
Stacks in DATA STRUCTUREStacks in DATA STRUCTURE
Stacks in DATA STRUCTURE
 
Data Structures and Algorithm Analysis
Data Structures  and  Algorithm AnalysisData Structures  and  Algorithm Analysis
Data Structures and Algorithm Analysis
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
 
Stack & Queue using Linked List in Data Structure
Stack & Queue using Linked List in Data StructureStack & Queue using Linked List in Data Structure
Stack & Queue using Linked List in Data Structure
 
Quick sort-Data Structure
Quick sort-Data StructureQuick sort-Data Structure
Quick sort-Data Structure
 
Big O Notation.ppt
Big O Notation.pptBig O Notation.ppt
Big O Notation.ppt
 
Time andspacecomplexity
Time andspacecomplexityTime andspacecomplexity
Time andspacecomplexity
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sorting
 
Selection sort
Selection sortSelection sort
Selection sort
 
Merge sort algorithm
Merge sort algorithmMerge sort algorithm
Merge sort algorithm
 
SINGLE SOURCE SHORTEST PATH.ppt
SINGLE SOURCE SHORTEST PATH.pptSINGLE SOURCE SHORTEST PATH.ppt
SINGLE SOURCE SHORTEST PATH.ppt
 
자료구조 2014-2018년 출석수업대체시험 기출문제
자료구조 2014-2018년 출석수업대체시험 기출문제자료구조 2014-2018년 출석수업대체시험 기출문제
자료구조 2014-2018년 출석수업대체시험 기출문제
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programming
 
Linear Search & Binary Search
Linear Search & Binary SearchLinear Search & Binary Search
Linear Search & Binary Search
 
자료구조 2014-2018년 기말시험 기출문제
자료구조 2014-2018년 기말시험 기출문제자료구조 2014-2018년 기말시험 기출문제
자료구조 2014-2018년 기말시험 기출문제
 

Similaire à Merge sort

c++ program I need to sort arrays using an insertion sort and a mer.pdf
c++ program I need to sort arrays using an insertion sort and a mer.pdfc++ program I need to sort arrays using an insertion sort and a mer.pdf
c++ program I need to sort arrays using an insertion sort and a mer.pdfdhavalbl38
 
#include iostream using namespace std; void InsertionSort(int .pdf
#include iostream using namespace std; void InsertionSort(int .pdf#include iostream using namespace std; void InsertionSort(int .pdf
#include iostream using namespace std; void InsertionSort(int .pdfbrijmote
 
DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024RUHULAMINHAZARIKA
 
time_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdftime_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdfSrinivasaReddyPolamR
 
Please I want a detailed complete answers for each part.Then make.pdf
Please I want a detailed complete answers for each part.Then make.pdfPlease I want a detailed complete answers for each part.Then make.pdf
Please I want a detailed complete answers for each part.Then make.pdfsiennatimbok52331
 
Merge Sort implementation in C++ The implementation for Mergesort gi.pdf
Merge Sort implementation in C++ The implementation for Mergesort gi.pdfMerge Sort implementation in C++ The implementation for Mergesort gi.pdf
Merge Sort implementation in C++ The implementation for Mergesort gi.pdfmdameer02
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqPradeep Bisht
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Sheik Uduman Ali
 
Using CUDA Within Mathematica
Using CUDA Within MathematicaUsing CUDA Within Mathematica
Using CUDA Within Mathematicakrasul
 
Using Cuda Within Mathematica
Using Cuda Within MathematicaUsing Cuda Within Mathematica
Using Cuda Within MathematicaShoaib Burq
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptxRamiHarrathi1
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptxKokilaK25
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.pptebinazer1
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structureShakil Ahmed
 

Similaire à Merge sort (20)

c++ program I need to sort arrays using an insertion sort and a mer.pdf
c++ program I need to sort arrays using an insertion sort and a mer.pdfc++ program I need to sort arrays using an insertion sort and a mer.pdf
c++ program I need to sort arrays using an insertion sort and a mer.pdf
 
#include iostream using namespace std; void InsertionSort(int .pdf
#include iostream using namespace std; void InsertionSort(int .pdf#include iostream using namespace std; void InsertionSort(int .pdf
#include iostream using namespace std; void InsertionSort(int .pdf
 
DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024DAA-Divide and Conquer methodology, DAA 2024
DAA-Divide and Conquer methodology, DAA 2024
 
time_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdftime_complexity_list_02_04_2024_22_pages.pdf
time_complexity_list_02_04_2024_22_pages.pdf
 
DAA Lab Work.docx
DAA Lab Work.docxDAA Lab Work.docx
DAA Lab Work.docx
 
Please I want a detailed complete answers for each part.Then make.pdf
Please I want a detailed complete answers for each part.Then make.pdfPlease I want a detailed complete answers for each part.Then make.pdf
Please I want a detailed complete answers for each part.Then make.pdf
 
1D Array
1D Array1D Array
1D Array
 
Merge Sort implementation in C++ The implementation for Mergesort gi.pdf
Merge Sort implementation in C++ The implementation for Mergesort gi.pdfMerge Sort implementation in C++ The implementation for Mergesort gi.pdf
Merge Sort implementation in C++ The implementation for Mergesort gi.pdf
 
pradeepbishtLecture13 div conq
pradeepbishtLecture13 div conqpradeepbishtLecture13 div conq
pradeepbishtLecture13 div conq
 
Merge sort
Merge sortMerge sort
Merge sort
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
Using CUDA Within Mathematica
Using CUDA Within MathematicaUsing CUDA Within Mathematica
Using CUDA Within Mathematica
 
Using Cuda Within Mathematica
Using Cuda Within MathematicaUsing Cuda Within Mathematica
Using Cuda Within Mathematica
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Array presentation
Array presentationArray presentation
Array presentation
 
01 - DAA - PPT.pptx
01 - DAA - PPT.pptx01 - DAA - PPT.pptx
01 - DAA - PPT.pptx
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
 
Recursive squaring
Recursive squaringRecursive squaring
Recursive squaring
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
 

Plus de Abdelrahman Saleh (6)

Hash table
Hash tableHash table
Hash table
 
Linear search
Linear searchLinear search
Linear search
 
binary search
binary searchbinary search
binary search
 
Selection sort
Selection sortSelection sort
Selection sort
 
Quick sort
Quick sortQuick sort
Quick sort
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 

Dernier

ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxruthvilladarez
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 

Dernier (20)

ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docx
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 

Merge sort

  • 2. List of contents ● Introduction ● Example w/ illustrating figures ● Algorithm ● implementation (Java, C++, Python) ● Performance Runtime ○ Best, Average and worst cases. ● Execution ● Other Notes
  • 3. Introduction ● Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. ● The merge() function is used for merging two halves The merge(a, l, m, r) is key process that assumes that a[l..m] and a[m+1..r] are sorted and merges the two sorted sub-arrays into one .
  • 5. Algorithm . ➔ Array name “arr” , left-most element “l”, right-most element “r” ● If r is bigger than l ○ Find the middle point to divide the array into two halves : ■ middle m = (l+r)/2 ○ Call mergeSort for first half : ■ Call mergeSort(arr, l, m) ○ Call mergeSort for second half : ■ Call mergeSort(arr, m+1, r) ○ Merge the two halves sorted in step 2 and 3 : ■ Call merge(arr, l, m, r)
  • 7. C++ void mergeSort(int arr[], int l, int r) { if (l < r) { //Same as (l+r)/2, but avoids overflow for large l and r . int m = l+(r-l)/2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m+1, r); merge(arr, l, m, r); } }
  • 8. C++ Continue ... void merge(int arr[], int l, int m, int r) { int i = 0, j = 0, k = 1 ; int n1 = m - l + 1; int n2 = r - m; int L[n1], R[n2]; /* create temp arrays */ /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; // Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
  • 9. C++ Continue ... /* Merge the temp arrays back into arr[l..r]*/ while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } // Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
  • 10. C++ Continue ... /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
  • 11. JAVA void mergeSort(int arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l+r)/2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr , m+1, r); merge(arr, l, m, r); } }
  • 12. JAVA Continue ... /* Merge the temp arrays back into arr[l..r]*/ void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; /* Create temp arrays */ int R[] = new int [n2]; /*Copy data to temp arrays*/ for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; // Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
  • 13. JAVA Continue ... int i = 0, j = 0, int k = l ; // Initial indexes of first, second and merged subarrays relatively . while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; }else{ arr[k] = R[j]; j++; } k++; } // Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
  • 14. JAVA Continue ... /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
  • 15. Python . def mergeSort(arr, l, r): if l < r : m = (l+(r-1))/2 #Same as (l+r)/2, but avoids overflow for large l and r #Sort first and second halves mergeSort(arr, l, m) mergeSort(arr, m+1, r) merge(arr, l, m, r)
  • 16. Python Continue ... def merge(arr, l, m, r): n1 = m - l - 1 n2 = r - m L = [0] * (n1) #create temp arrays R = [0] * (n2) #copy data to temp arrays for i in range (0, n1): L[i] = arr(l + i) for j in range (0, n2): R[j] = arr(m + 1 + j) // Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
  • 17. Python Continue ... i = 0 j = 0 k = l while i < n1 and j < n2: if L[i] <= R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[i] j += 1 // Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
  • 18. Python . #Copy the remaining elements of L[], if there are any while i < n1: arr[k] = L[i] i += 1 k += 11 #Copy the remaining elements of R[], if there are any while j < n2: arr[k] = R[j] j += 1 k += 1 // Merges two subarrays of arr[] : arr[l..m], arr[m+1..r]
  • 19. Performance Runtime ● Time complexity Θ(nlog(n)) . ● In merge sort Best, Average and Worst cases are the same “Θ(nlog(n))” as it always divides the array in two halves and take linear time to merge two halves.
  • 20. Execution . Input array : [4, 6, 3, 2, 1, 9, 7] Output Array: [1, 2, 3, 4, 6, 7, 9]
  • 21. Other Notes . ● Algorithmic Paradigm: Divide Approach ● Sorting In Place: No ● Stable: Yes ● Online: Yes