I am trying to sort an array of Strings using compareTo()
. This is my code:
static String Array[] = {" Hello ", " This ", "is ", "Sorting ", "Example"};
String temp;
public static void main(String[] args)
{
for (int j=0; j<Array.length;j++)
{
for (int i=j+1 ; i<Array.length; i++)
{
if (Array[i].compareTo(Array[j])<0)
{
String temp = Array[j];
Array[j] = Array[i];
Array[i] = temp;
}
}
System.out.print(Array[j]);
}
}
Now the output is:
Hello This Example Sorting is
I am getting results, but not the results I want to get, which are:
Hello This Example Is Sorting
How can I adjust my code to sort the string array properly?
I know this is a late reply but maybe it can help someone.
Removing whitespace can be done by using the trim() function. After that if you want to sort the array with case sensitive manner you can just use:
and for case insensitive manner:
Hope this helps!
Instead of this line
use this line
and you are good to go. The reason your current code is not working is explained by other users already. This above replacement is one workaround amongst several that you could apply.
To begin with, your problem is that you use the method `compareTo() which is case sensitive. That means that the Capital letters are sorted apart from the lower case. The reason is that it translated in Unicode where the capital letters are presented with numbers which are less than the presented number of lower case. Thus you should use `compareToIgnoreCase()` as many also mentioned in previous posts.
This is my full example approach of how you can do it effecively
After you create an object of the Comparator you can pass it in this version of `sort()` which defined in java.util.Arrays.
take a close look at super. This makes sure that the array which is passed into is combatible with the type of comparator.
The magic part of this way is that you can easily sort the array of strings in Reverse order you can easily do by:
Alternative Choice
The method
compareToIgnoreCase()
, although it works well with many occasions(just like compare string in english),it will wont work well with all languages and locations. This automatically makes it an unfit choice for use. To make sure that it will be suppoorted everywhere you should usecompare()
from java.text.Collator.You can find a collator for your location by calling the method
getInstance()
. After that you should set this Collator's strength property. This can be done with thesetStrength()
method together withCollator.PRIMARY
as parameter. With this alternative choise the IgnocaseComp can be written just like below. This version of code will generate the same output independently of the location" Hello " , " This " , "is ", "Sorting ", "Example"
First of all you provided spaces in
" Hello "
and" This "
, spaces have a lower value than alphabetic characters in Unicode, so it gets printed first. (The rest of the characters were sorted alphabetically).Now upper case letters have a lower value than lower case letter in Unicode, so "Example" and "Sorting" gets printed, then at last
"is "
which has the highest value.Apart from the alternative solutions that were posted here (which are correct), no one has actually answered your question by addressing what was wrong with your code.
It seems as though you were trying to implement a selection sort algorithm. I will not go into the details of how sorting works here, but I have included a few links for your reference =)
Your code was syntactically correct, but logically wrong. You were partially sorting your strings by only comparing each string with the strings that came after it. Here is a corrected version (I retained as much of your original code to illustrate what was "wrong" with it):
Further Reading
The problem with this approach is that its asymptotic complexity is O(n^2). In simplified words, it gets very slow as the size of the array grows (approaches infinity). You may want to read about better ways to sort data, such as quicksort.
Your output is correct. Denote the white characters of " Hello" and " This" at the beginning.
Another issue is with your methodology. Use the
Arrays.sort()
method:Output:
Here the third element of the array "is" should be "Is", otherwise it will come in last after sorting. Because the sort method internally uses the ASCII value to sort elements.