DAA File2
DAA File2
MERGE SORT
Aim: To perform time complexity analysis on MergeSort algorithm.
Merge Sort: Merge sort is defined as a sorting algorithm that works by
dividing an array into smaller subarrays, sorting each subarray, and then
merging the sorted subarrays back together to form the final sorted array.
Merge sort is a recursive algorithm that continuously splits the array in
half until it cannot be further divided i.e., the array has only one
element left (an array with one element is always sorted). Then the
sorted subarrays are merged into one sorted array.
Step 1: Initially divide the array into two equal halves.
Step 2: These subarrays are further divided into two halves. Now they
become array of unit length that can no longer be divided and array of unit
length are always sorted.
Step 3: These sorted subarrays are merged together, and we get bigger
sorted arrays
Step 4: This merging process is continued until the sorted array is built from
the smaller subarrays.
MERGE SORT-:
include<iostream>
include<chrono>
using namespace std;
using namespace chrono;
void merge(int arr[], int left, int middle, int right) { int n1 = middle - left + 1;
int n2 = right - middle;
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (left_array[i] <= right_array[j])
{
arr[k] = left_array[i]; i++;
}
else
{
arr[k] = right_array[j]; j++;
}
k++;
}
void mergeSort(int arr[], int left, int right) { if (left < right) {
int middle = left + (right - left) / 2;
int main() {
int size = 5000;
// int num = size; //Unsorted
int arr[size];
Time exity
Comple
Unsorted
1200
1000
800
600
400
200
0
0 1000 2000 3000 4000 5000 6000 7000 8000 9000
Size of Array
For Partially Sorted Array:
Size of Array Time Taken (ms)
1000 96
2000 263
3000 516
4000 453
5000 597
6000 724
7000 844
8000 997
1200
1000
800
600
400
200
0
0 1000 2000 3000 4000 5000 6000 7000 8000 9000
Size of Array