Professional Documents
Culture Documents
Daaoa Lab 4: Divide and Conquer
Daaoa Lab 4: Divide and Conquer
DAAOA Lab 4
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.
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){
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
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.
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).
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