Question

Programming with C++ language. Write and test a version of mergeSort using the following outline: Merge...

Programming with C++ language.

Write and test a version of mergeSort using the following outline:

Merge sort separates the array into 2 parts, sorts them and then uses a temporary array to merge them. Merge sort does its job recursively.

MergeSort(A, upper, lower)

if upper = lower then

     return

else

     middle := (upper + lower) / 2

     MergeSort(A, lower, middle)

     MergeSort(A, middle + 1, upper)

     Merge(A, lower, middle, upper)

end if

end MergeSort

Merge is non-recursive but is more complex than MergeSort because it has 3 jobs to do. The first job copies in order as many elements as it can from the lower and upper halves of the array to the temporary array. The second and third jobs are mutually exclusive. The second job copies the elements remaining in the lower half of the array to the temporary array. These elements are in order and are greater than the elements in the temporary array. The third job does the same things that the second job does but it does them to the upper half of the array. After Merge does two of the three jobs (it always does the first job and does exactly one of the second or third jobs), it copies the temporary array to the correct positions in the array.

The first loop does the first job; the second loop does the second job and the third loop does the third job. Why are the second and third jobs mutually exclusive? Look at the 3 loops’ loop conditions.

Merge(A, lower, middle, upper)

n := upper – lower + 1

B := createArray(n)

pos := 0

left := lower

right := middle + 1

while left <= middle and right <= upper

    if A[left] < A[right] then

       B[pos] := A[left]

       left := left + 1

    else

       B[pos] := A[right]

       right := right + 1   

    end if

    pos := pos + 1

end while

while left <= middle

    B[pos] := A[left]

    left := left + 1

    pos := pos + 1

end while

while right <= upper

    B[pos] := A[right]

    right := right + 1

    pos := pos + 1

end while

for pos := 0 to n – 1

    A[pos + lower] := B[pos]

end for

end Merge

It is not necessary to create B in Merge. We can create B as either a global, module, or class level variable.

Homework Answers

Answer #1

#include <iostream>
using namespace std;
#define MAX 10000
void merge(int array[],int low,int mid,int high )
{
   int temp[MAX];
   int i = low;
   int j = mid +1 ;
   int k = low ;

   while( (i <= mid) && (j <=high) )
   {
       if(array[i] <= array[j])
           temp[k++] = array[i++] ;
       else
           temp[k++] = array[j++] ;
   }
  
   while( i <= mid )
       temp[k++]=array[i++];
  
   while( j <= high )
       temp[k++]=array[j++];

   for(i= low; i <= high ; i++)
       array[i]=temp[i];
  
}

void merge_sort( int array[],int low, int high )
{
   int mid;
   if( low != high )
   {
       mid = (low+high)/2;
       merge_sort( array,low , mid );
       merge_sort( array,mid+1, high );
       merge( array,low, mid, high );
   }
}

int main()
{
   int i,n;
   int array[MAX];
   cout<<"Enter the number of elements : ";
   cin>>n;
   cout<<"Enter elements to be sorted : ";
   for(i=0;i<n;i++)
   {
       cin>>array[i];
   }
   merge_sort( array,0, n-1);
   cout<<"Sorted list is :\n";
   for( i = 0 ; i<n ; i++)
       cout<<array[i]<<" ";
   return 0;
}

Know the answer?
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
Similar Questions
DIRECTIONS: IMPLEMENT QuickSort and MergeSort. You have been provided: 1. Functions to perform Merge (for MergeSort)...
DIRECTIONS: IMPLEMENT QuickSort and MergeSort. You have been provided: 1. Functions to perform Merge (for MergeSort) and Partition (for QuickSort). 2. In class we discussed the body of the recursive functions, the "brakes" needed to stop the recursion. You are expected to develop 2 RECURSIVE programs: 1. Complete the bodies of the sort functions, MergeSort and QuickSort. 2. Complate the main that tests each function. - program should not read inputs - stock the program with multiple arrays (test cases)...
Complete the java code as per the comments public class Sorting {    ///////////////////////////////////////////////    //...
Complete the java code as per the comments public class Sorting {    ///////////////////////////////////////////////    // STEP 1 -- Make sorting methods generic    ///////////////////////////////////////////////       /**    * Re-orders the contents given array using the insertion sort algorithm.    *    * @param data The array to be sorted.    */    //TODO: Make me generic to work on any kind of Comparable data!    public static void insertionSort(int[] data)    {        int insert; // temporary...
CAN YOU PLEASE WRITE THIS CODE IN A DIFFERENT WAY 'EASIER AND BETTER' QUESTION Using C++...
CAN YOU PLEASE WRITE THIS CODE IN A DIFFERENT WAY 'EASIER AND BETTER' QUESTION Using C++ 11. Write a function that will merge the contents of two sorted (ascending order) arrays of type double values, storing the result in an array out- put parameter (still in ascending order). The function shouldn’t assume that both its input parameter arrays are the same length but can assume First array 04 Second array Result array that one array doesn’t contain two copies of...
Write a MIPS assembly program that sorts an array using bubble sort translating the C code...
Write a MIPS assembly program that sorts an array using bubble sort translating the C code int main(void) { int array[] = {10, 2, 7, 5, 15, 30, 8, 6}; // input array int arraySize = sizeof(array)/sizeof(array[0]); bool swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; //Note : "j" , "arraySize - j" are optimizations to the bubble sort algorithm j++; // j= sorted elements int i=0; /* "arraySize - j" is used...
Write a code in c++ using linear insertion following the steps below. Comment your work. 1....
Write a code in c++ using linear insertion following the steps below. Comment your work. 1.    Ask the user for the name of a file containing data. If it does not exist, the program should display an error, then ask for a new file name. Entering an asterisk (*) as the first and only character on a line should terminate the program. 2.     You can use a statically-allocated one-dimensional array of doubles for this with length 100. You...
Do a theta analysis and count the number of computations it performed in each function/method of...
Do a theta analysis and count the number of computations it performed in each function/method of the following code: import java.io.*; import java.util.Scanner; class sort { int a[]; int n; long endTime ; long totalTime; long startTime; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public sort(int nn) // Constructor { a = new int[nn]; n = nn; endTime= 0; totalTime =0; startTime =0; } public static void main(String args[]) throws IOException { System.out.print("\nEnter number of students: "); int nn =...
Modify the following code by JAVA language Write a static method totalDurations that is passed the...
Modify the following code by JAVA language Write a static method totalDurations that is passed the parallel arrays from the main program. It creates a new pair of parallel arrays (phone numbers and durations, again) where each different incoming phone number is stored exactly once, and the duration is the total duration of all the calls from that phone number. It then prints these arrays. Nothing is returned. For example, if the arrays contain 555-1234 (duration 10), 555-4321 (duration 20),...
Using c++ You may #include only: <iostream> <cmath> “functions.h” Write the function void readForceValuesFromStdIn(double* leftTeam, double*...
Using c++ You may #include only: <iostream> <cmath> “functions.h” Write the function void readForceValuesFromStdIn(double* leftTeam, double* rightTeam, unsigned const int noParticipants) that will read the list of forces exerted by each wizard alternating by the team into the correct array of doubles (see example in problem description) Define the function bool validForces(const double* forces, unsigned const int noParticipants) using the provided code. This function will be used to ensure that the forces exerted by each team’s wizard are non-negative The...
2. The following linear programming problem has been solved by The Management Scientist. Use the output...
2. The following linear programming problem has been solved by The Management Scientist. Use the output to answer the questions. LINEAR PROGRAMMING PROBLEM MAX 25X1+30X2+15X3 S.T. 1) 4X1+5X2+8X3<1200 2) 9X1+15X2+3X3<1500 OPTIMAL SOLUTION Objective Function Value = 4700.000 Variable Variable Reduced Cost X1 140.000   0.000 X2 0.000 10.000 X3 80.000 0.000 Constraint   Slack/Surplus Dual Price 1   0.000   1.000 2 0.000 2.333 OBJECTIVE COEFFICIENT RANGES Variable   Lower Limit Current Value Upper Limit X1 19.286 25.000 45.000 X2 No Lower Limit 30.000 40.000...
in C++ Please and thanks Here is a list of 6 numbers. Use the selection sort...
in C++ Please and thanks Here is a list of 6 numbers. Use the selection sort algorithm to sort this list. Fill in this table with each iteration of the loop in the selection sort algorithm. Mark the place from which you are looking for the 'next smallest element'. In this display, the upper numbers are the indices, the lower numbers are in the corresponding positions. Use the several rows provided to show the sequence of steps. 0 1 2...