Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 731
Sikander Avatar asked Oct 20 '12 07:10

Sikander


4 Answers

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.

like image 68
Juvanis Avatar answered Nov 13 '22 18:11

Juvanis


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):

static  String Array[]={" Hello " , " This " , "is ", "Sorting ", "Example"};
String  temp;

//Keeps track of the smallest string's index
int  shortestStringIndex; 

public static void main(String[] args)  
{              

 //I reduced the upper bound from Array.length to (Array.length - 1)
 for(int j=0; j < Array.length - 1;j++)
 {
     shortestStringIndex = j;

     for (int i=j+1 ; i<Array.length; i++)
     {
         //We keep track of the index to the smallest string
         if(Array[i].trim().compareTo(Array[shortestStringIndex].trim())<0)
         {
             shortestStringIndex = i;  
         }
     }
     //We only swap with the smallest string
     if(shortestStringIndex != j)
     {
         String temp = Array[j];
         Array[j] = Array[shortestStringIndex]; 
         Array[shortestStringIndex] = temp;
     }
 }
}

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.

like image 26
Prince Mabandla Avatar answered Nov 13 '22 17:11

Prince Mabandla


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:

Arrays.sort(yourArray);

and for case insensitive manner:

Arrays.sort(yourArray,String.CASE_INSENSITIVE_ORDER);

Hope this helps!

like image 10
RishikeshD Avatar answered Nov 13 '22 19:11

RishikeshD


Instead of this line

if(Array[i].compareTo(Array[j])<0)

use this line

if(Array[i].trim().compareTo(Array[j].trim())<0)

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.

like image 9
narayanf1 Avatar answered Nov 13 '22 19:11

narayanf1