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: {17,58,96,24,88,70,23,64,74,81,55}
public class NaturalMergeSorter {
public int getSortedRunLength(int[] array, int arrayLength, int startIndex){
// Check if startIndex is out of bounds
if (startIndex <0|| startIndex >= arrayLength){
return 0;
}
// Initialize the length of the sorted run
int runLength =1;
// Traverse the array to find the length of the sorted run
for (int i = startIndex +1; i < arrayLength; i++){
if (array[i]>= array[i -1]){
runLength++;
} else {
break;
}
}
return runLength;
}
public void naturalMergeSort(int[] array, int arrayLength){
if (arrayLength ==0){
return;
}
int i =0;
boolean isSorted = false;
while (!isSorted){
// Get the length of the first sorted run
int firstRunLength = getSortedRunLength(array, 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 = getSortedRunLength(array, arrayLength, secondRunStart);
// Merge the two runs
merge(array, i, i + firstRunLength -1, secondRunStart + secondRunLength -1);
// Update index i
i = secondRunStart + secondRunLength;
// If i has moved to the end or past the end, reset i to 0
if (i >= arrayLength){
i =0;
}
}
}
public void merge(int[] numbers, int leftFirst, int leftLast, int rightLast){
int mergedSize = rightLast - leftFirst +1;
int[] mergedNumbers = new int[mergedSize];
int mergePos =0;
int leftPos = leftFirst;
int rightPos = leftLast +1;
// Add smallest element from left or right partition to merged numbers
while (leftPos <= leftLast && rightPos <= rightLast){
if (numbers[leftPos]<= numbers[rightPos]){
mergedNumbers[mergePos]= numbers[leftPos];
leftPos++;
} else {
mergedNumbers[mergePos]= numbers[rightPos];
rightPos++;
}
mergePos++;
}
// If left partition isn't empty, add remaining elements to mergedNumbers
while (leftPos <= leftLast){
mergedNumbers[mergePos]= numbers[leftPos];
leftPos++;
mergePos++;
}
// If right partition isn't empty, add remaining elements to mergedNumbers
while (rightPos <= rightLast){
mergedNumbers[mergePos]= numbers[rightPos];
rightPos++;
mergePos++;
}
// Copy merged numbers back to numbers
System.arraycopy(mergedNumbers,0, numbers, leftFirst, mergedSize);
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!