Reputation: 17
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
Upvotes: 0
Views: 143
Reputation: 689
You need to take care for 2 things:
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();
}
}
Upvotes: 3
Reputation: 574
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.
Upvotes: 1