Word Sort

import java.io.*;
class WordSort
{
public static void main() throws IOException
{
InputStreamReader x= new InputStreamReader(System.in);
BufferedReader y= new BufferedReader(x);

String str[]=new String[1];

System.out.println(“Enter a string, terminated by a ‘.'”);
String s=y.readLine();
s=s+” “;
int i,j,k=0,l=s.length();
char ch;
String w=””,temp;

for(i=0;i<l;i++)
{
ch=s.charAt(i);
if(ch!=’ ‘)
{
w=w+ch;
}
else
{
str[k]=w;
k++;
w=””;
}
}

for(i=0;i<k;i++)
{
for(j=0;j<k-i-1;j++)
{
if(str[j].length()<str[j+1].length())
{
temp=str[j];
str[j]=str[j+1];
str[j+1]=temp;
}
if(str[j].length()==str[j+1].length())
{
if(str[j].compareTo(str[j+1])>0)
{
temp=str[j];
str[j]=str[j+1];
str[j+1]=temp;
}
}
}
}

for(i=0;i<k;i++)
{
System.out.print(str[i]+” “);
}
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s