Counting sort in Java Sorting characters
Write a program that sorts a given sequence of characters in the ascending order.
A sequence may include only the following characters: 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'.
It's recommended to use the counting sort algorithm. Other algorithms may get "Time limit exceeds" error.
Input data format
The first line contains the number of characters. The second one consists of characters.
Output data format
Output the characters in ascending order separated by space.
Sample Input 1:
5
e c b e a
Sample Output 1:
a b c e e
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] counts = new int[10];
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
counts[scanner.next().charAt(0) - 'a']++;
}
for (int i = 0; i < counts.length; i++) {
while (counts[i] > 0) {
System.out.print((char) (i + 'a') + " ");
counts[i]--;
}
}
}
}

浙公网安备 33010602011771号