Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Name: Ruturaj Uttarwar Class: TY ET-D

GR No: 12020036 Roll No: 60

DAAOA Lab 4

Implementation of Divide and Conquer in Merge Sort

Divide and Conquer:

A divide-and-conquer algorithm recursively breaks down a problem into two or more sub-problems
of the same or related type, until these become simple enough to be solved directly.

Divide and Conquer method in Merge sort.

Merge Sort is a Divide and Conquer algorithm. It divides the input array into two halves, calls itself
for the two halves, and then merges the two sorted halves. The merge () function is used for
merging two halves.

Code:
#include <iostream>
using namespace std;
void merge(int arr[],int l,int mid,int r)
{
int n1=mid-l+1;
int n2=r-mid;

int a[n1];
int b[n2];

for(int i=0;i<n1;i++){
a[i]=arr[l+i];
}

for(int i=0;i<n2;i++){
b[i]=arr[mid+1+i];
Name: Ruturaj Uttarwar Class: TY ET-D
GR No: 12020036 Roll No: 60

int i=0;
int j=0;
int k=l;

while (i<n1 && j<n2){


if (a[i]<b[j]){
arr[k]=a[i];
k++;
i++;
}
else{
arr[k]=b[j];
k++;
j++;
}
}

while (i<n1){
arr[k]=a[i];
k++;
i++;
}
while (i<n2){
arr[k]=a[j];
k++;
j++;
}
Name: Ruturaj Uttarwar Class: TY ET-D
GR No: 12020036 Roll No: 60

void mergesort(int arr[], int l, int r)


{
if (l<r){
int mid= (l+r)/2;
mergesort(arr,l,mid);
mergesort(arr,mid+1,r);

merge(arr,l,mid,r);
}
}

int main(){
int arr[]={5,4,3,2,1};
mergesort(arr,0,4);
for (int i=0;i<5;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
return 0;
}

Time-Complexity:

Merge Sort is a recursive algorithm and time complexity can be expressed as following recurrence
relation.

T(n) = 2T(n/2) + O(n)


Name: Ruturaj Uttarwar Class: TY ET-D
GR No: 12020036 Roll No: 60

The solution of the above recurrence is O(nLogn). The list of size N is divided into a max of Logn
parts, and the merging of all sublists into a single list takes O(N) time, the worst-case run time of
this algorithm is O(nLogn).

 Best Case Time Complexity: O(n*log n)

 Worst Case Time Complexity: O(n*log n)

 Average Time Complexity: O(n*log n)

The time complexity of MergeSort is O(n*Log n) in all the 3 cases (worst, average and best) as the
mergesort always divides the array into two halves and takes linear time to merge two halves.

Result:
Name: Ruturaj Uttarwar Class: TY ET-D
GR No: 12020036 Roll No: 60

You might also like