Reputation: 63
i'm trying to sort a string in java, below is my code:
public class SortingString {
public static void Sortstring(){
String str="String";
char [] charStr = str.toCharArray();
for (char value : charStr) {
System.out.println("Value = " + value);
}
Arrays.sort(charStr);
System.out.println("The sorted array is:");
for (char value : charStr) {
System.out.println("Value = " + value);
}
}
public static void main(String [] args){
Sortstring();
}
}
So when I give an input str="Java", it gives me:
Value = J
Value = a
Value = v
Value = a
The sorted array is:
Value = J
Value = a
Value = a
Value = v
And when I give input str="String", it gives me:
Value = S
Value = t
Value = r
Value = i
Value = n
Value = g
The sorted array is:
Value = S
Value = g
Value = i
Value = n
Value = r
Value = t
I don't understand why it isn't sorting all the characters. It's not sorting the first character but it is working well for rest of the characters in the String. What am I missing?
Upvotes: 1
Views: 150
Reputation: 13853
The sort method, when used on primitive arrays (such as char[]
, int[]
, etc) uses the relational operators (such as >
and <
) to compare different elements.
Since all uppercase letters are "lesser" than their lowercase counterparts, the resulting array is not being sorted alphabetically.
The expressions below will help you to understand what is happening during the execution of the sort algorithm:
'A' < 'a' // true
(int) 'A' // 65
(int) 'a' // 97
When the sort
method is executed on objects, the values returned by the compareTo
method (defined in Comparable
) are used to determine the order of the resulting array.
In case you wanna sort an array of Strings alphabetically (ignoring case) you could use the built-in CASE_INSENSITIVE_ORDER
Comparator. Example below:
Arrays.sort(arrayOfStrings, String.CASE_INSENSITIVE_ORDER);
Or else:
Collections.sort(listOfStrings, String.CASE_INSENSITIVE_ORDER);
Upvotes: 3
Reputation: 500237
What you are missing is that Latin uppercase letters compare less than Latin lowercase letters. The relevant part of the Unicode character code chart can be found here.
If you want this to behave differently, you need to supply your own comparator. See How to use Comparator in Java to sort
One way to achieve your desired behaviour is by having the comparator convert both letters to lowercase, and then compare the result.
Upvotes: 6