I am trying to construct a merge sort that will then return the sorted list as a String[], but the result has to be returned outside of the if statement, and I'm not sure how to go around doing that.
public static String[] mergeSort(String[] wordList) {
if (wordList.length >= 2) {
String[] left = new String[wordList.length / 2];
String[] right = new String[wordList.length - wordList.length / 2];
for (int i = 0; i < left.length; i ) {
left[i] = wordList[i];
}
for (int i = 0; i < right.length; i ) {
right[i] = wordList[i wordList.length / 2];
}
mergeSort(left);
mergeSort(right);
return merge(wordList, left, right);
}
}
public static String[] merge(String[] wordList, String[] left, String[] right) {
int a = 0;
int b = 0;
for (int i = 0; i < wordList.length; i ) {
if (b >= right.length || (a < left.length && left[a].compareToIgnoreCase(right[b]) < 0)) {
wordList[i] = left[a];
a ;
} else {
wordList[i] = right[b];
b ;
}
}
return wordList;
}
The code obviously doesn't work because the return is inside the if statement. Is there any simple way to extract the merge result?
CodePudding user response:
Just add an else
below the if-statement in your mergeSort
-method and return your wordList
:
else{
return wordList;
}
When the wordList
-parameter has a lenght smaller than 2, you don't need to sort it, so you can just return it in the else
-branch (An array with length 0 or 1 is already sorted).
CodePudding user response:
If the code flow reaches outside of the if condition loop, then it indicates that the array has only one element or no elements at all. Reason being, the inner if statement has a return statement, so method call always return from that statement if there are two or more elements in the array. So, you can simply add a return statement to return wordList outside the if loop.
{
if(...)
{
...
return ... ;
}
return wordList ;
}