Question: C ++ // Merge sort in C++ #include using namespace std; // Merge two subarrays L and M into arr void merge(int arr[], int p,
C ++
// Merge sort in C++
#include
// Merge two subarrays L and M into arr void merge(int arr[], int p, int q, int r) { // Create L A[p..q] and M A[q+1..r] int n1 = q - p + 1; int n2 = r - q;
int L[n1], M[n2];
for (int i = 0; i
// Maintain current index of sub-arrays and main array int i, j, k; i = 0; j = 0; k = p;
// Until we reach either end of either L or M, pick larger among // elements L and M and place them in the correct position at A[p..r] while (i
// When we run out of elements in either L or M, // pick up the remaining elements and put in A[p..r] while (i
while (j
// Divide the array into two subarrays, sort them and merge them void mergeSort(int arr[], int l, int r) { if (l
mergeSort(arr, l, m); mergeSort(arr, m + 1, r);
// Merge the sorted subarrays merge(arr, l, m, r); } }
// Print the array void printArray(int arr[], int size) { for (int i = 0; i
// Driver program int main() { int arr[] = {6, 5, 12, 10, 9, 1}; int size = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, size - 1);
cout 8.5 LAB: Merge sort The program is the same as shown at the end of the Merge sort section, with the following changes: - Numbers are entered by a user in a separate helper function, ReadNums(), instead of defining a specific array in main(). The first number is how many integers to be sorted, and the rest are the integers. - Output of the array has been moved to the helper function PrintNums (. - An output has been added to MergeSort(), showing the indices that will be passed to the recursive function calls. Add code to the merge sort algorithm to count the number of comparisons performed. Add code at the end of main() that outputs "comparisons: " followed by the number of comparisons performed (Ex: "comparisons: 12") Hint: Use a global variable to count the comparisons. Note: Take special care to look at the output of each test to better understand the merge sort algorithm. Ex: When the input is
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
