The first line gives the number of words n, and the second line gives n words separated by single spaces.
Sort the words ignoring case and print them on one line separated by single spaces.
The order of two words is decided by turning English uppercase letters into lowercase in both, then comparing character codes (ASCII).
Compare from the first character; the word whose first differing character has the smaller code comes first.
If one word equals the start of the other, the shorter one comes first.
Words that become equal in lowercase ("Bob" and "bob") keep the order in which they appear in the input.
The codes are 48 to 57 for digits 0 to 9, 95 for the underscore _, and 97 to 122 for lowercase a to z, so "_x" comes before "alice".
Input
1 ≤ n ≤ 2000. Each word has 1 to 20 characters and consists only of English uppercase and lowercase letters, digits and underscores (_)
Output
the n sorted words on one line, separated by single spaces
Example 1 · stdin
6
bob Alice _x alice Bob x9
stdout
_x Alice alice bob Bob x9
Example 2 · stdin
4
ab a AB a_
stdout
a a_ ab AB
main.py
Error List00F8 ↓ · ⇧F8 ↑
Input (stdin)
When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).
$ Ready
Open this on a computer to write and run code. On mobile you can read the problem and the solutions.
In other languagesShow solutions by language · 8 languages
There are three traps. First, a plain sort puts every uppercase letter (65 to 90) before every lowercase letter (97 to 122), so "Bob" comes before "alice". Second, comparing in uppercase moves the underscore _ (95) after the letters, which differs from comparing in lowercase. Python key=str.upper and C# StringComparer.OrdinalIgnoreCase (documented as equivalent to converting to uppercase) do that. Java compareToIgnoreCase and CASE_INSENSITIVE_ORDER compare in lowercase at the end, so they match this problem. JS localeCompare uses human-language rules rather than character codes, so _ lands elsewhere, and for the same spelling it puts lowercase first, which breaks input order. Third, keeping equal words in input order needs a stable sort. Python sorted, JS/TS sort (since ES2019), Java List.sort and C# OrderBy are stable. C# List.Sort and Array.Sort, C++ std::sort and C qsort do not promise stability. C++ uses std::stable_sort; C stores the arrival order in a struct and uses it as the last comparison key. On Linux (glibc), qsort usually happens to keep the order, so it may pass there, but on macOS it really mixes equal words; it is not a promise, so do not rely on it. Joining is Python " ".join(words), JS/TS words.join(" "), Java String.join(" ", words), C# string.Join(" ", words); C and C++ print a space before every word except the first. Craykon passes a function returning -1, 0 or 1 to words.Sort(byLower) (equal items keep their order) and joins with words.Join(" ").
Pythonmain.py · 4 lines
n = int(input())words = input().split()# sorted는 안정 정렬이라, 소문자로 같은 단어끼리는 들어온 차례를 지킨다print(" ".join(sorted(words, key=str.lower)))
JavaScriptmain.js · 9 lines
const [first, second] = require("fs").readFileSync(0, "utf8").split("\n");const words = second.trim().split(" ");const byLower = (a, b) => { const x = a.toLowerCase(); const y = b.toLowerCase(); return x < y ? -1 : x > y ? 1 : 0; // < 는 글자 코드 순(localeCompare 아님)};// Array.prototype.sort는 ES2019부터 안정 정렬이다console.log(words.sort(byLower).join(" "));
TypeScriptmain.ts · 10 lines
import { readFileSync } from "node:fs";const [, second] = readFileSync(0, "utf8").split("\n");const words: string[] = second.trim().split(" ");const byLower = (a: string, b: string): number => { const x: string = a.toLowerCase(); const y: string = b.toLowerCase(); return x < y ? -1 : x > y ? 1 : 0; // < 는 글자 코드 순(localeCompare 아님)};// Array.prototype.sort는 ES2019부터 안정 정렬이다console.log(words.sort(byLower).join(" "));
JavaMain.java · 18 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Arrays;import java.util.Comparator;import java.util.List;import java.util.Locale;public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); in.readLine(); List<String> words = Arrays.asList(in.readLine().trim().split(" ")); // List.sort(객체)는 안정 정렬(TimSort). 소문자로 바꾼 것을 글자 코드로 비교한다 words.sort(Comparator.comparing((String w) -> w.toLowerCase(Locale.ROOT))); System.out.println(String.join(" ", words)); }}
C#Main.cs · 14 lines
using System;using System.Linq;class Program{ static void Main() { Console.ReadLine(); string[] words = Console.ReadLine().Trim().Split(' '); // OrderBy는 안정 정렬. Ordinal은 글자 코드 순(문화권 규칙 없이) var sorted = words.OrderBy(w => w.ToLowerInvariant(), StringComparer.Ordinal); Console.WriteLine(string.Join(" ", sorted)); }}
C++main.cpp · 22 lines
#include <algorithm>#include <cctype>#include <iostream>#include <string>#include <vector>static std::string lower(std::string s) { for (char& c : s) c = (char)std::tolower((unsigned char)c); return s;}int main() { int n; std::cin >> n; std::vector<std::string> words(n); for (auto& w : words) std::cin >> w; // std::sort는 안정 정렬이 아니다: 같은 것끼리 차례를 지키려면 stable_sort std::stable_sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) { return lower(a) < lower(b); }); for (int i = 0; i < n; i++) std::cout << (i ? " " : "") << words[i]; std::cout << '\n';}
Cmain.c · 31 lines
#include <ctype.h>#include <stdio.h>#include <stdlib.h>struct Word { char text[21]; int order; /* 들어온 차례: qsort는 안정 정렬이 아니라서 직접 비교에 넣는다 */};static int by_lower(const void *pa, const void *pb) { const struct Word *a = pa, *b = pb; const unsigned char *x = (const unsigned char *)a->text, *y = (const unsigned char *)b->text; while (*x && tolower(*x) == tolower(*y)) x++, y++; int d = tolower(*x) - tolower(*y); /* 한쪽이 끝나면 '\0'(0)이라 짧은 쪽이 앞 */ if (d != 0) return d; return a->order - b->order;}int main(void) { static struct Word w[2000]; int n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%20s", w[i].text); w[i].order = i; } qsort(w, n, sizeof w[0], by_lower); for (int i = 0; i < n; i++) printf(i ? " %s" : "%s", w[i].text); printf("\n"); return 0;}
Craykonmain.cray · 21 lines
n = Console.ReadLine().ToNumber();words = Console.ReadLine().Split();// 정렬(기준함수)는 같은 것끼리 들어온 차례를 지킨다words.Sort(byLower);Console.WriteLine(words.Join(" "));// 소문자로 바꾼 것을 글자 코드 순으로 비교byLower(앞, 뒤){ a = 앞.ToLower(); b = 뒤.ToLower(); if (a < b) { return -1; } if (a > b) { return 1; } return 0;}