You are currently viewing Sort the characters Ascending/Descending in a given String

Sort the characters Ascending/Descending in a given String

Problem Statement: Given a String, Sort the characters in Ascending/Descending from a given String and return the String



Test Cases

Test Case – 1
Input:  bushansirgur
Output:  abghinrrssuu
Test Case – 2
Input:  bharathsirgur
Output:  aabghhirrrstu



Java Source Code
public class SortCharactersInWord {
	public static void main(String[] args) {
		System.out.println(sortCharacters("bushansirgur"));
		System.out.println(sortCharacters("bharathsirgur"));
	}
	public static String sortCharacters(String str){
	    char[] c = str.toCharArray();
	    for(int i = 0; i < c.length - 1; i++){
	        for(int j = i + 1; j < c.length; j++){
	            if(c[i] > c[j]){
	                char temp = c[i];
	                c[i] = c[j];
	                c[j] = temp;
	            }
	        }
	    }
	    return new String(c);
	}
}



Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply