Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Can you please fix the code!! ( Should be in c + + ) The code is in the pictures added. 1 5 . 1
Can you please fix the code!! Should be in c The code is in the pictures added. 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:
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:
the output is:
unsorted:
sorted: #include
#include
using namespace std;
int comparisons ; Global variable to count comparisons
void Mergevector& numbers, int left, int mid, int right
int n mid left ;
int n right mid;
vector Ln Rn;
for int i ; i n; i
Li numbersleft i;
for int j ; j n; j
Rj numbersmid j;
int i j k left;
while i n && j n
if Li Rj
numbersk Li;
else
numbersk Rj;
comparisons; Increment comparison count
while i n
numbersk Li;
while j n
numbersk Rj;
void MergeSortvector& numbers, int left, int right
if left right
int mid left right left;
cout left mid mid right endl;
MergeSortnumbers left, mid;
MergeSortnumbers mid right;
Mergenumbers left, mid, right;
void ReadNumsvector& numbers
int size;
cin size;
numbers.resizesize;
for int i ; i size; i
cin numbersi;
void PrintNumsconst vector& numbers
for int num : numbers
cout num ;
cout endl;
int main
vector numbers;
ReadNumsnumbers;
cout "unsorted: ;
PrintNumsnumbers;
cout endl;
MergeSortnumbers numbers.size;
cout endl;
cout "sorted: ;
PrintNumsnumbers;
cout "comparisons: comparisons endl;
return ;
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started