Question

1. rite a C++ program that implements the merge sort recursive algorithm. For simplicity you may hard-code the list of elements to order. Additionally, you may order elements in increasing or decreasing order, your call. Sample Output Elements to so 8 2 4 69 7 10 1 5 3 Results using merge sort 1 2 3 4 5 6 7 8 9 10

Here's my code in C++ so far. I don't understand how to split the array into subarrays then sort each subarray to merge into a final sorted array

0 0
Add a comment Improve this question Transcribed image text
Answer #1

HI, Please find my implementation.

Please let me know in case of any issue.


#include <iostream>
using namespace std;

// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

/* create temp arrays */
int L[n1], R[n2];

/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];

/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}

/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}

/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}

/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;

// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);

merge(arr, l, m, r);
}
}

/* Function to print an array */
void displayElement(int A[], int size)
{
for (int i=0; i < size; i++)
cout<<A[i]<<" ";
cout<<endl;
}

/* Driver program to test above functions */
int main()
{
int arr[] = {8,2,4,6,9,7,10,1,5,3};
int arr_size = 10;

cout<<"Elements to sort: "<<endl;;
displayElement(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

cout<<"\nResult using merge sort: "<<endl;;
displayElement(arr, arr_size);
return 0;
}

secondweek secondweek g++ mergeSort.cpp secondweek /a.out Elements to sort: 8 246 9 7 10 15 3 Result using merge sort: 1 2 34 56789 10 secondweek

Add a comment
Know the answer?
Add Answer to:
Here's my code in C++ so far. I don't understand how to split the array into...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please merge all the codes below and add comments using JAVA Program. I need a complete...

    Please merge all the codes below and add comments using JAVA Program. I need a complete code which is the combination of the following codes: // Merges the left/right elements into a sorted result. // Precondition: left/right are sorted public static void merge(int[] result, int[] left,                                        int[] right) {     int i1 = 0;   // index into left array     int i2 = 0;   // index into right array     for (int i = 0; i < result.length; i++)...

  • Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. E...

    Modify the sorts (selection sort, insertion sort, bubble sort, quick sort, and merge sort) by adding code to each to tally the total number of comparisons and total execution time of each algorithm. Execute the sort algorithms against the same list, recording information for the total number of comparisons and total execution time for each algorithm. Try several different lists, including at least one that is already in sorted order. ---------------------------------------------------------------------------------------------------------------- /** * Sorting demonstrates sorting and searching on an...

  • please help urgent c++ Use the vector/array below for the following tasks: {25, 39, 12, 85,...

    please help urgent c++ Use the vector/array below for the following tasks: {25, 39, 12, 85, 55, 69, 40, 75} Task1 - [2 points] Put your name on the top comment section as the author of this code. For example, // Author: (Your name] Task2 – [5 points] Display (cout) the elements that are greater than 40 in the array. Task 3 - [5 points] Sort the given input array in an ascending order using any sort algorithm learned from...

  • HW58.1. Array Merge Sort You've done merge (on Lists), so now it's time to do merge...

    HW58.1. Array Merge Sort You've done merge (on Lists), so now it's time to do merge sort (on arrays). Create a public non-final class named Mergesort that extends Merge. Implement a public static method int[] mergesort(int[] values) that returns the input array of ints sorted in ascending order. You will want this method to be recursive, with the base case being an array with zero or one value. If the passed array is null you should return null. If the...

  • 1) can any one please givem the code for this a) If n is a power...

    1) can any one please givem the code for this a) If n is a power of 2, as it is in Figure 9-3, you would merge pairs of individual entries, starting at the beginning of the array. Then you would return to the beginning of the array and merge pairs of twoentry subarrays. Finally, you would merge one pair of four-entry subarrays. Notice that the subarrays in each pair of subarrays contain the same number of entries. In general,...

  • Consider the following mergeSortHelper method, which is part of an algorithm to recursively sort an array...

    Consider the following mergeSortHelper method, which is part of an algorithm to recursively sort an array of integers. /**  Precondition: (arr.length == 0 or 0 <= from <= to <= arr.length) * arr.length == temp.length */ public static void mergeSortHelper(int[] arr, int from, int to, int[] temp) { if (from < to) { int middle = (from + to) / 2; mergeSortHelper(arr, from, middle, temp); mergeSortHelper(arr, middle + 1, to, temp); merge(arr, from, middle, to, temp); } } The merge method...

  • please check my answers if it wrong answer me a) (25 points) Suppose that you are...

    please check my answers if it wrong answer me a) (25 points) Suppose that you are asked to analyze the performance. Algorithms operate on 1D array of size nor 2D a of the algorithms below, write down the Big O or order of grow terms of n. If the algorithm cannot be applied to the array, write 0(1), O(log n), O(n), O(n logn), 90), O(n"), O(n!). The will only be given for reasonable Big O answers. & algorithms for their...

  • Please use pseudocode for this response, any additional advice for making this as easy to understand...

    Please use pseudocode for this response, any additional advice for making this as easy to understand as possible is greatly appreciated. Problem Statement Assume the Scores array is parallel to the Players array (both arrays are below). Scores array Scores[0] = 198 Scores[1] = 486 Scores[2] = 651 Scores[3] = 185 Scores[4] = 216 Scores[5] = 912 Scores[6] = 173 Scores[7] = 319 Scores[8] = 846 Scores[9] = 989 Players Array Players[0] = "Joe" Players[1] = "Ann" Players[2] = "Marty"...

  • PLEASE READ CAREFULLY AND ALL THE WAY THROUGH!!! I already asked this question but unfortunately the...

    PLEASE READ CAREFULLY AND ALL THE WAY THROUGH!!! I already asked this question but unfortunately the person who answered it did not read it. There is a sorting algorithm, “Stooge-Sort” which is named after the comedy team, "The Three Stooges." if the input size, n, is 1or 2, then the algorithm sorts the input immediately. Otherwise, it recursively sorts the first 2n/3 elements, then the last 2n/3 elements, and then the first 2n/ 3 elements again. The details are shown...

  • Module B: A state rand0%4; if (A state1) global time 6 Module C: private int C state parametersi,よ1;//acall with...

    Module B: A state rand0%4; if (A state1) global time 6 Module C: private int C state parametersi,よ1;//acall without defining parameterjis fine if (i9%2) C state 7: else C state- 100 return C state +randOA if((module) Crand0M) > 10) Module D: < "good"くくendl; cout 5. Coding with quality reqwst Provide brief analyses justifications of the time complexities for all questions (a) (8 pts) For a sorted array A of n different elements ranging from I to n. Suppose one element...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT