Uploaded by AWPacademy kingstar

TY ET-D 69 DAAOA Lab4

advertisement
Name: Aryan Waghresha
Gr.No.: 11911321
Class: TY ET-D
Roll.no.: 69
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 subproblems 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,intmid,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++){
Name: Aryan Waghresha
Gr.No.: 11911321
b[i]=arr[mid+1+i];
}
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++;
Class: TY ET-D
Roll.no.: 69
Name: Aryan Waghresha
Gr.No.: 11911321
Class: TY ET-D
Roll.no.: 69
j++;
}
}
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[]={56,42,13,21,11};
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)
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).
Name: Aryan Waghresha
Gr.No.: 11911321

Best Case Time Complexity: O(n*log n)

Worst Case Time Complexity: O(n*log n)

Average Time Complexity: O(n*log n)
Class: TY ET-D
Roll.no.: 69

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:
Sorted Array:
Download