|
-
Jun 24th, 2007, 12:47 PM
#1
Thread Starter
Frenzied Member
sort string
Hello, I am trying to write a simple sort string without using the array sort method. But it's not working. please help
Code:
public static String sort(String s) {
StringBuffer s1 = new StringBuffer(s);
s1.sort();
return s1.toString();
}
-
Jun 24th, 2007, 02:57 PM
#2
Re: sort string
I don't know what you are trying to achieve. But here is some code that uses a simple buble sort
Code:
public static String sort(String string)
{
for(int i=0;i<string.length()-1;i++)
for(int j=i+1;j<string.length();j++)
if(Character.toLowerCase(string.charAt(j))<Character.toLowerCase(string.charAt(i)))
string = swap(string,i,j);
return string;
}
private static String swap(String s, int i, int j)
{
char[] chars=s.toCharArray();
char tmp=chars[i];
chars[i]=chars[j];
chars[j]=tmp;
return new String(chars);
}
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
Jun 25th, 2007, 11:16 PM
#3
Thread Starter
Frenzied Member
Re: sort string
Hello, yeah it works. but could you explain to me about the code below? I could not get it at all, especially with 2 dimensional arrays:
Code:
private static String swap(String s, int i, int j)
{
char[] chars=s.toCharArray();
char tmp=chars[i];
chars[i]=chars[j];
chars[j]=tmp;
return new String(chars);
}
-
Jun 26th, 2007, 07:46 AM
#4
Re: sort string
Code:
private static String swap(String s, int i, int j)
{
// Convert String to char array
char[] chars=s.toCharArray();
// store char number i in temporary variable
char tmp=chars[i];
// replace char[i] with char[j]
chars[i]=chars[j];
// replace char [j] with the temp value (old i value)
chars[j]=tmp;
// Return a new string from the partially sorted char array
return new String(chars);
}
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|