# Thread: Help with algorithm for sorting an array of Strings

1. Member Join Date
Jul 2011
Posts
10
Rep Power
0

## 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)
Java 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:
Java 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 Last edited by Fubarable; 07-11-2011 at 12:09 AM.  Reply With Quote

2. ## Moderator edit: changed thread title from "help me" to "Help with algorithm for sorting an array of Strings".  Reply With Quote

3. ## 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.  Reply With Quote

4. Member Join Date
Jul 2011
Posts
10
Rep Power
0

## here
Java 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.  Reply With Quote

5. ## 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.
Java 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.  Reply With Quote

6. ## Java 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)```  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•