Sort the characters of a String
  • Posted: 5 years ago
  • Updated: 4 years ago
  • Edit
  • answers (1)
  • views (2836)

How will you sort the characters of a String in increasing order?


Posted Answers



public static void stringSort(String string){

/* String to character array */
char[] charArray = string.toCharArray();

/* Iterate through the array */
for (int i = 0; i < string.length - 1; i++){
for (int j = i + 1; j < string.length; j++){

int st = Character.toLowerCase(charArray[i])
- Character.toLowerCase(charArray[j]);
/* Case insensitive comparison */
if ( st == 0 )
/* letters are the same */
st = charArray[i] - charArray[j];

/* Case sensitive comparison */
if (st > 0){
int temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
}
}
}
}


Time complexity = \( O(n^{2}) \).

You need to Sign In to post your solution.