3.3.3 Merge Sort
3.3.3 Merge Sort
2
Mission of the Department
4
Program Educational Objectives
PEO1 Demonstrate analytical and design skills including the ability to generate creative solutions and foster
team-oriented professionalism through effective communication in their careers.
PEO2 Expertise in successful careers based on their understanding of formal and practical methods of
application development using the concept of computer programming languages and design principles in
accordance to industry 4.0
PEO3 Exhibit the growth of the nation and society by implementing and acquiring knowledge of upliftment of
health, safety and other societal issues.
PEO4 Implement their exhibiting critical thinking and problem- solving skills in professional practices or tackle
social, technical and business challenges.
5
Program Specific Outcomes
6
Topic To be Covered
• Merge Sort is one of the most popular sorting algorithms that is based
on the principle of Divide and Conquer Algorithm.
• A problem is divided into multiple sub-problems. Each sub-problem is
solved individually. Finally, sub-problems are combined to form the
final solution.
Merge Sort Algorithm
mergesort(array,beg,end)
1. Start
2. declare array and left, right, mid variable
3. perform merge function.
mergesort(array,left,right)
mergesort (array, left, right)
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
4. Stop
Program of Merge Sort
#include<iostream> while(i<nl) { //extra element in left array
using namespace std; array[k] = larr[i];
void swapping(int &a, int &b) { //swap the content of a and b i++; k++;
int temp; }
temp = a; while(j<nr) { //extra element in right array
a = b;
array[k] = rarr[j];
b = temp;
j++; k++;
}
void display(int *array, int size) { }
for (int i = 0; i<size; i++) }void mergeSort(int *array, int l, int r) {
cout << array[i] << " "; int m;
cout << endl; if (l < r) {
} int m = l+(r-l)/2; // Sort first and second arrays
void merge(int *array, int l, int m, int r) { mergeSort(array, l, m);
int i, j, k, nl, nr; //size of left and right sub-arrays mergeSort(array, m+1, r);
nl = m-l+1; nr = r-m; merge(array, l, m, r);
int larr[nl], rarr[nr]; //fill left and right sub-arrays }
for(i = 0; i<nl; i++) }
larr[i] = array[l+i]; int main() {
for(j = 0; j<nr; j++)
int n;
rarr[j] = array[m+1+j];
cout << "Enter the number of elements: ";
i = 0; j = 0; k = l; //marge temp arrays to real array
while(i < nl && j<nr) { cin >> n;
if(larr[i] <= rarr[j]) { int arr[n]; //create an array with given number of elements
array[k] = larr[i]; cout << "Enter elements:" << endl;
i++; for(int i = 0; i<n; i++) {
} cin >> arr[i];
else{ }
array[k] = rarr[j]; cout << "Array before Sorting: ";
j++; display(arr, n);
} mergeSort(arr, 0, n-1); //(n-1) for last index
k++; cout << "Array after Sorting: ";
} display(arr, n);
}
Complexity of merge sort
https://www.youtube.com/watch?v=jlHkDBEumP0
THANK YOU