Professional Documents
Culture Documents
A 160 Exp 5 DAA Samrudhi Patil
A 160 Exp 5 DAA Samrudhi Patil
Experiment-5
a. Set mid as the index of the middle element of the array, i.e., (left + right) /
2
b. Recursively call MergeSort for the left half of the array, i.e.,
MergeSort(arr, left, mid)
c. Recursively call MergeSort for the right half of the array, i.e.,
MergeSort(arr, mid + 1, right)
d. Merge the sorted left and right halves using the merge function, i.e.,
merge(arr, left, mid, right)
SVKM’s NMIMS
Mukesh Patel School of Technology Management & Engineering Shirpur Campus
- n1 = mid - left + 1
- n2 = right - mid
2. Create temporary arrays L and R to hold the elements of the two subarrays
3. Copy the data from the main array arr to the temporary arrays L and R
4. Merge the elements of L and R back into the main array arr:
b. Compare elements of L and R one by one, and copy the smaller element to
arr
c. Increment the index of the subarray from which the element was copied
and the index of the merged array
Code:
#include <iostream>
#include <vector>
vector<int> L(n1);
vector<int> R(n2);
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
k++;
arr[k] = L[i];
i++;
k++;
arr[k] = R[j];
j++;
k++;
}
SVKM’s NMIMS
Mukesh Patel School of Technology Management & Engineering Shirpur Campus
int main() {
// Example usage
int n = arr.size();
mergeSort(arr, 0, n - 1);
return 0;
Output:
Time Complexity:
The time complexity of the Merge Sort algorithm implemented in the above
code is O(n log n).
Conclusion: