Java Program to sort the given string in reverse order using Comparator

Program

import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;
public class SortStringsInReverseUsingComparator {
    public String sortStringsReverse(String string)
    {
        Character tempArray[] = new Character[string.length()];
        for (int i = 0; i < string.length(); i++) {
            tempArray[i] = string.charAt(i);
        }     
        Arrays.sort(tempArray, new Comparator<Character>(){
            @Override
            public int compare(Character c1, Character c2)
            {               
                return Character.compare(c2, c1);
            }
        });
        StringBuilder sb = new StringBuilder(tempArray.length);
        for (Character c : tempArray)
        sb.append(c.charValue());
        return sb.toString();
    }
    public static void main(String[] args){
        SortStringsInReverseUsingComparator sortStringsInReverseUsingComparator = new SortStringsInReverseUsingComparator();
        Scanner reader = new Scanner(System.in);
        System.out.print("Enter a string to sort: ");
        String enteredString = reader.nextLine();
        String sortedString = sortStringsInReverseUsingComparator.sortStringsReverse(enteredString);
        System.out.println("Sorted String is "+ sortedString);                
    }
}

This program sorts the characters of a given string in reverse alphabetical order using a custom Comparator.

  1. Input:

    • The program takes a string from the user.
  2. Logic:

    • Converts the input string into an array of Character objects.
    • Uses Arrays.sort() with a custom Comparator to sort the characters in reverse order:
      • The comparator swaps the order of comparison using Character.compare(c2, c1) (reverse of the default behavior).
    • Converts the sorted Character array back into a string using a StringBuilder.
  3. Steps:

    • Convert the input string into a Character array.
    • Use Arrays.sort() with a comparator to sort characters in descending order.
    • Convert the sorted Character array into a string using StringBuilder.
  4. Output:

    • The sorted string in reverse order is printed.
  5. Key Features:

    • Custom Sorting:
      • The comparator allows sorting characters in reverse order.
    • Efficient Conversion:
      • Uses a StringBuilder to assemble the sorted characters back into a string.
  6. Example Execution:

    • Input:
      Enter a string to sort: banana
      
    • Process:
      • Convert "banana" to ['b', 'a', 'n', 'a', 'n', 'a'] (Character array).
      • Sort in reverse alphabetical order: ['n', 'n', 'b', 'a', 'a', 'a'].
      • Convert back to string: "nnbaaa".
    • Output:
      Sorted String is nnbaaa
      
  7. Comparator Explanation:

    • The comparator Character.compare(c2, c1) compares characters in reverse order, so higher ASCII values appear first.
  8. Complexity:

    • Time Complexity: O(n log n) for sorting.
    • Space Complexity: O(n) for the temporary Character array and result string.
  9. Use Case:

    • This program is useful for situations where reverse alphabetical ordering is required, such as creating a leaderboard in descending order.

Comparison with Alphabetical Sort:

  • The only difference is the comparator logic. Here, Character.compare(c2, c1) sorts in reverse, while Character.compare(c1, c2) sorts alphabetically.

Output

$ javac SortStringsInReverseUsingComparator.java
$ java SortStringsInReverseUsingComparator
Enter a string to sort: oodlescoop
Sorted String is spooooledc