Contents

Baekjun No. 2751, Sorting numbers 2 (with.Java)

   Aug 3, 2025     2 min read

This article explores Baekjoon Problem 2751, Sorting Numbers 2 (with Java).

We will learn by solving coding test problems, reflecting on previous problems, and exploring different solution methods.

Let’s first look at the problem.

Problem

Given N numbers, write a program to sort them in ascending order.

Input

The first line contains the number N (1 ≀ N ≀ 1,000,000).

The second and subsequent N lines contain numbers.

These numbers are integers whose absolute values are less than or equal to 1,000,000.

Numbers cannot be duplicated.

Output

Sort the results in ascending order on the first N lines, one per line.

Problem Solution

import java.util.PriorityQueue;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.IOException;

class Main{
    public static void main(String[] args) throws IOException {
    PriorityQueue<Integer> queue = new PriorityQueue<>();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    int len = Integer.valueOf(br.readLine().trim());

    for(int i = 0; i < len; i++){
        queue.offer(Integer.valueOf(br.readLine().trim()));
    }
    br.close();

    while(!queue.isEmpty()){
        bw.write(String.valueOf(queue.poll()));
        if(!queue.isEmpty()){
            bw.newLine();
        }
    }
    bw.flush();
    bw.close();
    }
}

Solution Explanation

First, it uses a PriorityQueue to store integers.

It uses a BufferedReader to receive input, and a BufferedWriter to output them.

The first line of input contains the number of numbers, which is stored in the len variable.

Then, it loops through the input and adds each number to the queue.

After all numbers have been received, it retrieves each number from the PriorityQueue and outputs it using the BufferedWriter.

After each number is output, it adds a line break to format it correctly.

Finally, it flushes and closes the BufferedWriter to terminate the program.

This program provides a function to efficiently input, sort, and output numbers.

Thank you!