Posted by: Sourav | April 24, 2015

Sort String using StringBuilder in Java


class m{

public static void main(String args[])
{
int i,j;
String s=”hgyutidbca”;
String r=””;
char c;
char temp;
StringBuilder news = new StringBuilder(s);
//int n=(int) s;//get ascii value
//char c=(char) 97; //ascii value to character

for(i=0;i<s.length();i++)
{
c=news.charAt(i);

for( j=i+1;j<s.length();j++)
{
c=news.charAt(i);

System.out.println(“i is =”+c);
System.out.println(“j is =”+news.charAt(j));
if((int) news.charAt(i)>(int) news.charAt(j))
{
System.out.println(“greater”);
c=news.charAt(j);
System.out.println(“c is now inside j = “+news.charAt(j));
//char[] chars = s.toCharArray();
System.out.println(“i is “+i +” and j is = “+j);
temp=news.charAt(i);
System.out.println(“temp is “+temp);
news.setCharAt(i, news.charAt(j));
System.out.println(“news is “+news);
news.setCharAt(j, temp);
System.out.println(“news is “+news);
System.out.println(“replaced “+temp + ” with “+news.charAt(j));
System.out.println(“news is “+news);
//temp=chars[i];
//chars[i]=chars[j];
//chars[j]=temp;
//s = String.valueOf(chars);
System.out.println(“inside j s is = “+news);
}
}

r=r+c;
System.out.println(“inside i s is = “+news);
System.out.println(“r is = “+r);

}
System.out.println(r);
System.out.println(“s is = “+news);
}
}

Advertisements

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

Categories

%d bloggers like this: