Practical 3
Practical 3
Practical 3
1) Aim: Implement and analyze the algorithm of Merge sort.
Program:
#include <iostream>
using namespace std;
int c=0;
c++;//j=0;
for (int j = 0; j < n2; j++)
{
c++;//j<n1
c++;//j++
c++;//RightArray[j] = a[mid + 1 + j];
RightArray[j] = a[mid + 1 + j];
}
c++;//for false condition
i = 0,j = 0,k = beg;
c++;//i = 0,j = 0,k = beg;
while (i < n1 && j < n2)
{
c++;//i < n1 && j < n2
c++;//if condition
if(LeftArray[i] <= RightArray[j])
{
c++;// a[k] = LeftArray[i];
a[k] = LeftArray[i];
ID No.:22IT109 Page 1
IT265– Design & Analysis of Algorithm 4IT (2023-24)
c++;//i++;
i++;
}
else
{
a[k] = RightArray[j];
c++;// a[k] = RightArray[j];
j++;
c++;//j++;
}
c++;//k++
k++;
}
c++;//false condition while
while (i<n1)
{
c++;//i<n1
c++;//a[k] = LeftArray[i];
a[k] = LeftArray[i];
c++;//i++;
i++;
c++;//k++;
k++;
}
c++;//false condition while
while (j<n2)
{
c++;//j<n2
c++;//a[k] = RightArray[j];
a[k] = RightArray[j];
c++;// j++;
j++;
c++;//k++
k++;
}
c++;//false condition while
}
ID No.:22IT109 Page 2
IT265– Design & Analysis of Algorithm 4IT (2023-24)
int main()
{
//int a[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};
int a[] ={25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
//int a[] ={13,12,11,10,9,8,7,6,5,4,3,2,1,14,15,16,17,18,19,20,21,22,23,24,25};
int n = sizeof(a) / sizeof(a[0]);
cout<<"Before sorting array elements are - \n";
printArray(a, n);
mergeSort(a, 0, n - 1);
cout<<"\nAfter sorting array elements are - \n";
printArray(a, n);
cout<<"\nCount "<<c;
return 0;
}
Output:
ID No.:22IT109 Page 3
IT265– Design & Analysis of Algorithm 4IT (2023-24)
Analysis Table:
Graph:
BEST CASE:
ID No.:22IT109 Page 4
IT265– Design & Analysis of Algorithm 4IT (2023-24)
BEST CASE
1400
1200 f(x) = 159.519382626683 x^1.3013942936642
1000
800
Count
600
400
200
0
5 10 15 20 25
Input
AVERAGE CASE:
Average Case
1400
1000
800
COUNT
600
400
200
0
5 10 15 20 25
INPUT
WORST CASE:
ID No.:22IT109 Page 5
IT265– Design & Analysis of Algorithm 4IT (2023-24)
Worst case
1400
1000
800
Count
600
400
200
0
5 10 15 20 25
Input
Conclusion: Merge Sort time complexity for best case , average case , worst case is O(nlogn).
ID No.:22IT109 Page 6
IT265– Design & Analysis of Algorithm 4IT (2023-24)
public:
Output:
ID No.:22IT109 Page 7
IT265– Design & Analysis of Algorithm 4IT (2023-24)
sum=sum+a[j]-a[i];
ans=max(sum,ans+a[j]);
maximum=max(maximum,ans);
i++;
j++;
}
return maximum;
}
};
// Driver code
int main() {
long long int t;
cin >> t;
while (t--) {
long long int n, k, i;
cin >> n;
long long int a[n];
for (i = 0; i < n; i++) {
cin >> a[i];
}
cin >> k;
Solution ob;
cout << ob.maxSumWithK(a, n, k) << endl;
}
return 0;
}
ID No.:22IT109 Page 8
IT265– Design & Analysis of Algorithm 4IT (2023-24)
ID No.:22IT109 Page 9