Why does my sorting loop seem to append an element where it shouldn't?

Sikander picture Sikander · Oct 20, 2012 · Viewed 249.1k times · Source

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?

Answer

Juvanis picture Juvanis · Oct 20, 2012

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:

String[] strings = { " Hello ", " This ", "Is ", "Sorting ", "Example" };
Arrays.sort(strings);

Output:

 Hello
 This
Example
Is
Sorting

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.