数字排序
第一行给出整数个数 n,第二行给出 n 个整数。
按从小到大的顺序用一个空格隔开输出在一行。
相同的数出现几次就输出几次。
- 输入
- 1 ≤ n ≤ 1000,-2,000,000,000 ≤ 每个整数 ≤ 2,000,000,000
- 输出
- 排好序的 n 个数,一行
4 10 9 2 -5
-5 2 9 10
第一行给出整数个数 n,第二行给出 n 个整数。
按从小到大的顺序用一个空格隔开输出在一行。
相同的数出现几次就输出几次。
4 10 9 2 -5
-5 2 9 10
运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。
$ 就绪
请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。
JS 和 TS 的 a.sort() 没有比较函数时会把数字转成字符串按字典序排列,[10, 9, 2] 会变成 10 2 9。
一定要写 a.sort((x, y) => x - y)(JS 的数是浮点数,这里用减法是安全的)。
相反,在 C 的 qsort 比较函数里返回 a - b,20 亿 - (-20 亿) 会溢出 int,顺序就反了,所以写 (a > b) - (a < b)。
其他语言默认按数值大小排序:Python sorted(a),Java Arrays.sort(a),C# Array.Sort(a),C++ std::sort,Craykon a.排序()。
n = int(input())a = sorted(map(int, input().split()))print(*a)const [n, ...a] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);a.sort((x, y) => x - y);console.log(a.join(" "));import { readFileSync } from "node:fs";const [n, ...a]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);a.sort((x, y) => x - y);console.log(a.join(" "));import java.util.Arrays;import java.util.Scanner;import java.util.StringJoiner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); Arrays.sort(a); StringJoiner out = new StringJoiner(" "); for (int x : a) out.add(String.valueOf(x)); System.out.println(out); }}using System;using System.Linq; class Program{ static void Main() { Console.ReadLine(); int[] a = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); Array.Sort(a); Console.WriteLine(string.Join(" ", a)); }}#include <algorithm>#include <iostream>#include <vector> int main() { int n; std::cin >> n; std::vector<int> a(n); for (int& x : a) std::cin >> x; std::sort(a.begin(), a.end()); for (int i = 0; i < n; i++) std::cout << (i ? " " : "") << a[i]; std::cout << "\n";}#include <stdio.h>#include <stdlib.h> static int ascending(const void *pa, const void *pb) { int a = *(const int *)pa, b = *(const int *)pb; return (a > b) - (a < b);} int main(void) { int n, a[1000]; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]); qsort(a, n, sizeof a[0], ascending); for (int i = 0; i < n; i++) printf(i ? " %d" : "%d", a[i]); putchar('\n'); return 0;}n = 控制台.读行().转数字();a = 控制台.读数字();a.排序();控制台.输出(a);