首页 > 试题广场 >

【模板】排序

[编程题]【模板】排序
  • 热度指数:8835 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
\hspace{15pt}给定一个长度为 n 的整数数组 A(允许元素重复),请将其按非递减顺序排序并输出。

输入描述:
\hspace{15pt}第一行输入整数 n\left(1\leqq n\leqq 10^5\right),表示数组长度。
\hspace{15pt}第二行输入 n 个整数 a_1,a_2,\dots,a_n\left(-10^9\leqq a_i\leqq 10^9\right)


输出描述:
\hspace{15pt}在一行上输出排序后的数组,各元素以空格分隔。
示例1

输入

5
5 4 3 2 1

输出

1 2 3 4 5
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
//Java
public class Main {
    public static void main(String[] args) {
       Scanner in=new Scanner(System.in);

        in.nextInt();
        ArrayList<Integer> list=new ArrayList<>();

        while (in.hasNext()){
            list.add(in.nextInt());
        }
        list.sort(Comparator.naturalOrder());
        list.forEach(s->{System.out.print(s+" ");});
    }
}

发表于 2025-10-17 13:06:33 回复(1)
用TreeSte
import java.util.Scanner;
import java.util.TreeSet;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        TreeSet<Integer> tre = new TreeSet<>();

        for(int i=0; i<n; i++){
            tre.add(in.nextInt());
        }

        for(int x: tre){
            System.out.print(x+" ");
        }
    }
}


发表于 2025-09-27 16:40:39 回复(0)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNextLine()) {
            String a = in.nextLine();
            String b = in.nextLine();
            String[] array = Arrays.stream(b.split(" ")).sorted(Comparator.comparing(Integer::valueOf)).toArray(String[]::new);
            System.out.println(String.join(" ", array));
        }
    }
}

发表于 2025-09-19 11:38:58 回复(0)
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        // 使用BufferedReader提高输入效率,适合处理大规模输入
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());

        // 读取数组元素
        String[] parts = br.readLine().split(" ");
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(parts[i]);
        }

        // 排序数组(非递减顺序)
        Arrays.sort(arr);

        // 构建输出字符串
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            if (i > 0) {
                sb.append(" ");
            }
            sb.append(arr[i]);
        }

        // 输出结果
        System.out.println(sb.toString());
    }
}

发表于 2025-08-29 12:34:39 回复(0)