so far i've done
public class U7_L6_Activity_One {
public static void sortAndPrintReverse(String [] arr) {
for (int j = 1; j < arr.length; j ) {
String temp = arr[j];
int possibleIndex = j;
while (possibleIndex > 0 && temp.compareTo(arr[possibleIndex - 1]) < 0) {
arr[possibleIndex] = arr[possibleIndex - 1];
possibleIndex--;
}
arr[possibleIndex] = temp;
for (String str : arr) {
System.out.print(str " ");
}
System.out.println();
}
}
}
but i'm unable to pass three of the test cases and am not sure how to fix the code
CodePudding user response:
You need to take care for 2 things:
- If size of array is 1 then it should print the single element as is.
temp.compareTo(arr[possibleIndex - 1]) > 0
should be done since the question asks to be reverse sorted (descending order).
public static void sortAndPrintReverse(String [] arr) {
// size is 1
if(arr.length==1){
for (String str : arr) {
System.out.print(str " ");
}
return;
}
for (int j = 1; j < arr.length; j ) {
String temp = arr[j];
int possibleIndex = j;
while (possibleIndex > 0 && temp.compareTo(arr[possibleIndex - 1]) > 0) {
arr[possibleIndex] = arr[possibleIndex - 1];
possibleIndex--;
}
arr[possibleIndex] = temp;
for (String str : arr) {
System.out.print(str " ");
}
System.out.println();
}
}
CodePudding user response:
Just swap the compareTo
condition from
temp.compareTo(arr[possibleIndex - 1]) < 0
to
temp.compareTo(arr[possibleIndex - 1]) > 0
Then the output meets the expectations.