Question: My code keeps failing the NaturalMergeSort ( ) method and keeps parring the getSortedRunLength ( ) method. I need to be able to pass all
My code keeps failing the NaturalMergeSort method and keeps parring the getSortedRunLength method. I need to be able to pass all tests and need helping correcting the code to pass all tests.
Array:
public class NaturalMergeSorter
public int getSortedRunLengthint array, int arrayLength, int startIndex
Check if startIndex is out of bounds
if startIndex startIndex arrayLength
return ;
Initialize the length of the sorted run
int runLength ;
Traverse the array to find the length of the sorted run
for int i startIndex ; i arrayLength; i
if arrayi arrayi
runLength;
else
break;
return runLength;
public void naturalMergeSortint array, int arrayLength
if arrayLength
return;
int i ;
boolean isSorted false;
while isSorted
Get the length of the first sorted run
int firstRunLength getSortedRunLengtharray arrayLength, i;
If the first run covers the entire array, it's sorted
if firstRunLength arrayLength i
isSorted true;
break;
Find the second run
int secondRunStart i firstRunLength;
int secondRunLength getSortedRunLengtharray arrayLength, secondRunStart;
Merge the two runs
mergearray i i firstRunLength secondRunStart secondRunLength ;
Update index i
i secondRunStart secondRunLength;
If i has moved to the end or past the end, reset i to
if i arrayLength
i ;
public void mergeint numbers, int leftFirst, int leftLast, int rightLast
int mergedSize rightLast leftFirst ;
int mergedNumbers new intmergedSize;
int mergePos ;
int leftPos leftFirst;
int rightPos leftLast ;
Add smallest element from left or right partition to merged numbers
while leftPos leftLast && rightPos rightLast
if numbersleftPos numbersrightPos
mergedNumbersmergePos numbersleftPos;
leftPos;
else
mergedNumbersmergePos numbersrightPos;
rightPos;
mergePos;
If left partition isn't empty, add remaining elements to mergedNumbers
while leftPos leftLast
mergedNumbersmergePos numbersleftPos;
leftPos;
mergePos;
If right partition isn't empty, add remaining elements to mergedNumbers
while rightPos rightLast
mergedNumbersmergePos numbersrightPos;
rightPos;
mergePos;
Copy merged numbers back to numbers
System.arraycopymergedNumbers numbers, leftFirst, mergedSize;
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
