Going further · 17
Sorting
Put values in order: smallest first, largest first, or by a rule you choose.
Sorting puts values in order.
The example below sorts numbers smallest first and largest first, then sorts words alphabetically and "shortest first".
nums = list(map(int, input().split()))words = input().split()print(*sorted(nums))print(*sorted(nums, reverse=True))print(*sorted(words))print(*sorted(words, key=lambda w: (len(w), w)))const [line1, line2] = require("fs").readFileSync(0, "utf8").trim().split("\n");const nums = line1.trim().split(/\s+/).map(Number);const words = line2.trim().split(/\s+/);console.log([...nums].sort((a, b) => a - b).join(" "));console.log([...nums].sort((a, b) => b - a).join(" "));console.log([...words].sort().join(" "));const byLength = (a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0);console.log([...words].sort(byLength).join(" "));import { readFileSync } from "node:fs";const [line1, line2]: string[] = readFileSync(0, "utf8").trim().split("\n");const nums: number[] = line1.trim().split(/\s+/).map(Number);const words: string[] = line2.trim().split(/\s+/);console.log([...nums].sort((a, b) => a - b).join(" "));console.log([...nums].sort((a, b) => b - a).join(" "));console.log([...words].sort().join(" "));const byLength = (a: string, b: string): number => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0);console.log([...words].sort(byLength).join(" "));import java.util.*;import java.util.stream.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int[] nums = Arrays.stream(sc.nextLine().trim().split("\\s+")).mapToInt(Integer::parseInt).toArray(); String[] words = sc.nextLine().trim().split("\\s+"); Arrays.sort(nums); System.out.println(Arrays.stream(nums).mapToObj(String::valueOf).collect(Collectors.joining(" "))); Integer[] boxed = Arrays.stream(nums).boxed().toArray(Integer[]::new); Arrays.sort(boxed, Comparator.reverseOrder()); System.out.println(Arrays.stream(boxed).map(String::valueOf).collect(Collectors.joining(" "))); String[] abc = words.clone(); Arrays.sort(abc); System.out.println(String.join(" ", abc)); Arrays.sort(words, Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder())); System.out.println(String.join(" ", words)); }}using System;using System.Linq; class Program{ static void Main() { int[] nums = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); string[] words = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries); Array.Sort(nums); Console.WriteLine(string.Join(" ", nums)); Console.WriteLine(string.Join(" ", nums.OrderByDescending(x => x))); Console.WriteLine(string.Join(" ", words.OrderBy(w => w, StringComparer.Ordinal))); var byLength = words.OrderBy(w => w.Length).ThenBy(w => w, StringComparer.Ordinal); Console.WriteLine(string.Join(" ", byLength)); }}#include <algorithm>#include <functional>#include <iostream>#include <sstream>#include <string>#include <vector> template <typename T>void print(const std::vector<T>& v) { for (size_t i = 0; i < v.size(); i++) std::cout << (i > 0 ? " " : "") << v[i]; std::cout << '\n';} int main() { std::string line; std::getline(std::cin, line); std::istringstream in1(line); std::vector<int> nums; for (int x; in1 >> x;) nums.push_back(x); std::getline(std::cin, line); std::istringstream in2(line); std::vector<std::string> words; for (std::string w; in2 >> w;) words.push_back(w); std::sort(nums.begin(), nums.end()); print(nums); std::sort(nums.begin(), nums.end(), std::greater<int>()); print(nums); std::sort(words.begin(), words.end()); print(words); std::sort(words.begin(), words.end(), [](const std::string& a, const std::string& b) { if (a.size() != b.size()) return a.size() < b.size(); return a < b; }); print(words);}#include <stdio.h>#include <stdlib.h>#include <string.h> int asc(const void *a, const void *b) { int x = *(const int *)a, y = *(const int *)b; return (x > y) - (x < y);}int desc(const void *a, const void *b) { return asc(b, a); }int abc(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }int by_length(const void *a, const void *b) { const char *s = *(char *const *)a, *t = *(char *const *)b; size_t ls = strlen(s), lt = strlen(t); if (ls != lt) return ls < lt ? -1 : 1; return strcmp(s, t);} int main(void) { char line[4096], wline[4096], *words[1000]; int nums[1000], n = 0, m = 0; fgets(line, sizeof line, stdin); fgets(wline, sizeof wline, stdin); for (char *p = strtok(line, " \r\n"); p; p = strtok(NULL, " \r\n")) nums[n++] = atoi(p); for (char *p = strtok(wline, " \r\n"); p; p = strtok(NULL, " \r\n")) words[m++] = p; qsort(nums, n, sizeof nums[0], asc); for (int i = 0; i < n; i++) printf(i > 0 ? " %d" : "%d", nums[i]); printf("\n"); qsort(nums, n, sizeof nums[0], desc); for (int i = 0; i < n; i++) printf(i > 0 ? " %d" : "%d", nums[i]); printf("\n"); qsort(words, m, sizeof words[0], abc); for (int i = 0; i < m; i++) printf(i > 0 ? " %s" : "%s", words[i]); printf("\n"); qsort(words, m, sizeof words[0], by_length); for (int i = 0; i < m; i++) printf(i > 0 ? " %s" : "%s", words[i]); printf("\n"); return 0;}nums = Console.ReadNumbers();words = Console.ReadLine().Split(); // 앞이 먼저면 음수, 뒤가 먼저면 양수큰것먼저(앞, 뒤){ return 뒤 - 앞;} 짧은것먼저(앞, 뒤){ if (앞.Length != 뒤.Length) { return 앞.Length - 뒤.Length; } if (앞 < 뒤) { return -1; } if (앞 > 뒤) { return 1; } return 0;} nums.Sort();Console.WriteLine(nums);nums.Sort(큰것먼저);Console.WriteLine(nums);words.Sort();Console.WriteLine(words);words.Sort(짧은것먼저);Console.WriteLine(words);10 9 1 25 3 pear fig banana kiwi apple
1 3 9 10 25 25 10 9 3 1 apple banana fig kiwi pear fig kiwi pear apple banana
Key points
- By default, numbers go by size and strings by dictionary order (character-code order).
- Some sorts return a new list and some change the list in place.
Pythonsorted(nums)returns a new list;nums.sort()works in place. - There are two ways to give a rule.
A key function says what to compare for each value (Pythonkey=lambda w: (len(w), w)means "by length, then alphabetically"). - A compare function takes two values and returns a negative number if the first goes first, 0 if they tie, and a positive number if the second goes first.
- A stable sort keeps tied values in their original order.
With a sort that is not stable, write the tie-break (same length → alphabetical) into the compare function too.
How each language writes it
| Python | sorted(nums) (new list), nums.sort() (in place).Largest first with reverse=True, a rule with key=lambda w: (len(w), w).Stable |
|---|---|
| JavaScript | arr.sort((a, b) => a - b) — in place.Without a compare function even numbers are compared as strings. Chain rules with a.length - b.length || ....Stable since ES2019 |
| TypeScript | Same as JavaScript |
| Java | Arrays.sort, Collections.sort.Largest first with Comparator.reverseOrder(), a rule with Comparator.comparingInt(String::length).thenComparing(...).Object arrays and Collections.sort are stable.int[] takes no comparator |
| C# | Array.Sort and List.Sort (in place, not guaranteed stable), LINQ OrderBy(...).ThenBy(...) and OrderByDescending (stable) |
| C++ | std::sort(v.begin(), v.end()), largest first with std::greater<int>().A compare lambda returns a bool: "does the first go first?".Use std::stable_sort when you need stability |
| C | qsort(a, n, sizeof a[0], cmp) — cmp takes two pointers and returns negative, 0 or positive.Not guaranteed stable |
| Craykon | list.Sort() sorts smallest first.Pass a compare function's name, as in list.Sort(ShortestFirst).Stable |
Common mistakes
Sorting numbers with plain sort()JavaScript · TypeScript
console.log([10, 9, 1].sort());→ [ 1, 10, 9 ] — the numbers are compared as strings
Always pass (a, b) => a - b for numbers.
Writing nums = nums.sort()Python
nums = [3, 1, 2]
nums = nums.sort()
print(nums)→ None — sort works in place and returns nothing
Write just nums.sort(), or nums = sorted(nums).
Passing a comparator for an int[]Java
int[] a = {3, 1, 2};
Arrays.sort(a, Comparator.reverseOrder());→ Compile error — the int[] version of sort takes no comparator
Convert to Integer[] as the example does, or sort smallest first and read backwards.
How languages differ
Writing a C
-2000000000 - 2000000000), flipping the sign and the order.
Compare instead:
Writing a C
qsort comparator as return a - b; overflows int when you subtract a large positive from a large negative (e.g.-2000000000 - 2000000000), flipping the sign and the order.
Compare instead:
(a > b) - (a < b).