hithit
hithit

Reputation: 17

insertion sort and printing values

the prompt says enter image description here

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 enter image description here enter image description here enter image description here

Upvotes: 0

Views: 143

Answers (2)

KL_KISNE_DEKHA_HAI
KL_KISNE_DEKHA_HAI

Reputation: 689

You need to take care for 2 things:

  1. If size of array is 1 then it should print the single element as is.
  2. 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

Newerth
Newerth

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

Related Questions