# Sorting in string

• 02-22-2012, 08:32 AM
BlueBird
Sorting in string
I have to write a code for sorting a sentence according to its length. If the length of two or more words are equal I then have to print the words like they were in the original string.
Like-the sky is blue.
Output- is the sky blue
I applied a simple bubble sort but that sorts the words with the same length in an alphabetical order and is giving me the output- "is sky the blue".
There needs to be another condition with can compare the indexes of the words of the same length and then maybe compare them to the original string.
I just can't get what the code should be.

My code:
I first used the string tokenizer and saved the words in an array. then,
for(int i=0;i<c-1;i++)
{
for(int j=i+1;j<c;j++)
{
if(a[i].length()>a[j].length())
{
String t=a[i];
a[i]=a[j];
a[j]=t;
}
else if(a[i].length()==a[j].length())
{
//I don't know what i should write here :P

}
}
}

Help will be really appreciated :)
• 02-22-2012, 08:34 AM
Eranga
Re: Sorting in string
Do you want to sort the words of a sentence according to the length of the word, isn't it?
• 02-22-2012, 08:43 AM
BlueBird
Re: Sorting in string
Yes, but there's a condition that follows which i've mentioned above..
• 02-22-2012, 08:49 AM
Eranga
Re: Sorting in string
Split the sentence by space. Add them into a array list and sort. That is all you have do.
• 02-22-2012, 08:53 AM
BlueBird
Re: Sorting in string
Yes I did that. But I don't want the words with the same length to be sorted alphabetically. I need them to be placed the same way they were in the original string.
Input- the lines are printed in reverse order
Output- in the are lines order printed reverse
On applying a simple sort acc. to the length my output is --> in are the lines printed reverse which is not the output which i want :/
• 02-22-2012, 10:11 AM
Eranga
Re: Sorting in string
So you have to keep the index too. According to your example "the lines are printed in reverse order", words "the" and "are" in same length and you want to keep them in the same order. So before sort the list you can extract that segment and place it accordingly.

• 02-22-2012, 10:36 AM
DarrylBurke
Re: Sorting in string
Prepare a stack of blank cards, or you could even use post-it notes. Write one word of the sentence on each. Arrange them on a table to form the sentence.

Then sort them manually, according to the terms of the assignment. Once you can do that systematically, transform your logical steps into code.

db
• 02-22-2012, 06:58 PM
BlueBird
Re: Sorting in string
Even if i save the index positions when the length is equal. I just don't know how on earth should i put it in my sorted array. I'll have to search my sorted array for those words
then swap them with the ones whose indexes i've saved. I don't know. This is killing me. :( Nothing makes sense.
• 02-28-2012, 11:10 AM
Eranga
Re: Sorting in string
Did you solve this out. I couldn't logged into the forum last few days.