# Help with algorithm for sorting an array of Strings

• 07-10-2011, 11:07 PM
eIO
Help with algorithm for sorting an array of Strings
Hi!
I the beginning programmer.
I want the sorted not repeating! sequence in outpute file.
this code: sorted sequence in outpute file.(Alphabetically)
Code:

```class SortString {   static String arr[] =     {"ddd", "sss", "aaa", "ggg", "aaa", "bbb",        "ddd", "ccc",  };   public static void main(String args[])     {     for (int j = 0; j < arr.length; j++)     {           for (int i = j + 1; i < arr.length; i++)       {         if (arr[i].compareTo(arr[j]) < 0)         {           String t = arr[j];           arr[j] = arr[i];           arr[i] = t;         }       }        System.out.println(arr[j]);       }     } }```

My algorithm solving not repeating sequence:
Code:

```for (int j = 0; j < arr.length; j++);     {     int j = 0;         for (int b = j + 1; b < arr.length +1; b++)         {       if  ( arr[j].equals(arr[b]) )     {                           clear( arr[b]);               }     }   }```
i think - clear(arr[b]) - delete repeating lines
Such algorithm is possible?
(If yes)How to connect the top program to this algorithm?
If it is not difficult:)-:
• 07-10-2011, 11:10 PM
Fubarable
Moderator edit: changed thread title from "help me" to "Help with algorithm for sorting an array of Strings".

• 07-10-2011, 11:45 PM
Norm
Quote:

delete repeating lines
For arrays, to remove an internal element means that you have to move all of the elements above the one to be removed down one. Also there must be a counter that keeps track of the number of good elements in the array.
• 07-11-2011, 06:08 AM
eIO
here
Code:

```String prevItem = null; for (final String item : arr){     if (!item.equals(prevItem)){         System.out.println(item);        }     prevItem = item; }```
anyone can write an example of the counter?
just wondering.
• 07-11-2011, 10:09 AM
Dark
You should be able to use the Array's sort method to put it in alphabetical order. Then check if the value of the array index is equal to the value of the index-1.
Code:

```for(int i=0; i<myArray.length();i++) {     if (myArray[i].equals(myArray[i-1])           //dont print     else         //print }```
Of course you have to check to see if you can even do that check without getting a indexOutOfBounds error, but I'm not going to write your program for you.
• 07-11-2011, 01:40 PM
Norm
Code:

```for(int i=1; i<myArray.length();i++)  // Start with index = 1 {     if (myArray[i].equals(myArray[i-1])  // Compare this(i) to previous element(i-1)```