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();
}
Printable View
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();
}
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);
}
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);
}
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);
}