Question: 1 7 . 1 3 LAB: Merge sort The class is the same as shown at the end of the Merge sort section, with the
LAB: Merge sort
The class 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 method, 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 method printNums
An output has been added to mergeSort
showing the indices that will be passed to the recursive method 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 static 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:
comparisons:
import java.util.Scanner;
public class LabProgram
Read size and create an array of size ints.
Read size ints, storing them in the array.
Return the array.
public static int readNums
Scanner scnr new ScannerSystemin;
int size scnrnextInt; Read array size
int nums new intsize; Create array
for int j ; j size; j Read the numsbers
numsj scnrnextInt;
return nums; Return the array
Output the numbers in nums, separated by spaces.
No space or newline will be output before the first number or after the last.
public static void printNumsint nums
for int i ; i nums.length; i
System.out.printnumsi;
if i nums.length
System.out.print;
public static void mergeint numbers, int i int j int k
int mergedSize k i ;
int mergedNumbers new intmergedSize;
int mergePos;
int leftPos;
int rightPos;
mergePos ;
leftPos i;
rightPos j ;
while leftPos j && rightPos k
if numbersleftPos numbersrightPos
mergedNumbersmergePos numbersleftPos;
leftPos;
else
mergedNumbersmergePos numbersrightPos;
rightPos;
mergePos;
while leftPos j
mergedNumbersmergePos numbersleftPos;
leftPos;
mergePos;
while rightPos k
mergedNumbersmergePos numbersrightPos;
rightPos;
mergePos;
for mergePos ; mergePos mergedSize; mergePos
numbersi mergePos mergedNumbersmergePos;
public static void mergeSortint numbers int i int k
int j;
if i k
j i k;
Trace output added to code in book
System.out.printfd d d d
i j j k;
mergeSortnumbers i j;
mergeSortnumbers j k;
mergenumbers i j k;
public static void mainString args
int numbers readNums;
System.out.printunsorted: ;
printNumsnumbers;
System.out.println
;
mergeSortnumbers numbers.length ;
System.out.print
sorted: ;
printNumsnumbers;
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
