Home > Enterprise >  insertion sort and printing values
insertion sort and printing values

Time:01-24

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

CodePudding user response:

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();
        }
    }

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.

  • Related