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?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…