Comparing two string and sorting them in alphabetical order

Viewed 61401

I want to compare two strings and sort them in alphabetical order. I am currently creating two arrays with the strings and sorting one them comparing the two arrays.

String a="LetterA";
String b="ALetterB";
String[] array1={a.toLowerCase(),b.toLowerCase()};
String[] array2={a.toLowerCase(),b.toLowerCase()};
Arrays.sort(array2);
if (Arrays.equals(array1, array2)){
    System.out.println(a+" is before "+b);
}
else{
    System.out.println(b+" is before "+a);
}

This works but it is time and memory consuming. I would appreciate if anyone can suggest a better way to do this.

4 Answers

Here is the code for the problem.

 public static void main(String[] args) {
    String a="Angram";
    String b="Angram";

    if(a.length()==b.length()) {
        char c[]=a.toCharArray();
        char d[]=b.toCharArray();
        Arrays.sort(c);
        Arrays.sort(d);
        a=new String(c);
        b=new String(d);
        if(a.equals(b)) 
            System.out.print("Yes");
        else
            System.out.print("No");
    }
    else {
        System.out.print("No");
    }
}
Related