정렬
배열의 원소를 순서대로 나열하는 알고리즘을 배워 봅시다.
1단계 2750 수 정렬하기
N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오.
첫째 줄에 수의 개수 N(1 ≤ N ≤ 1,000)이 주어진다. 둘째 줄부터 N개의 줄에는 수 주어진다. 이 수는 절댓값이 1,000보다 작거나 같은 정수이다. 수는 중복되지 않는다.
첫째 줄부터 N개의 줄에 오름차순으로 정렬한 결과를 한 줄에 하나씩 출력한다.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N;
N = sc.nextInt();
int[] array = new int[N];
for(int i=0; i<N; i++) {
array[i] = sc.nextInt();
}
Arrays.sort(array);
for(int value : array) {
System.out.println(value);
}
}
}
2단계 2751 수 정렬하기 2
N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오.
첫째 줄에 수의 개수 N(1 ≤ N ≤ 1,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 수가 주어진다. 이 수는 절댓값이 1,000,000보다 작거나 같은 정수이다. 수는 중복되지 않는다.
첫째 줄부터 N개의 줄에 오름차순으로 정렬한 결과를 한 줄에 하나씩 출력한다.
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N;
N = sc.nextInt();
StringBuilder sb = new StringBuilder();
ArrayList<Integer> list = new ArrayList<>();
for(int i=0; i<N; i++) {
list.add(sc.nextInt());
}
Collections.sort(list);
for(int value : list) {
sb.append(value).append('\n');
}
System.out.println(sb);
}
}
3단계 10989 수 정렬하기 3
N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오.
첫째 줄에 수의 개수 N(1 ≤ N ≤ 10,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 수가 주어진다. 이 수는 10,000보다 작거나 같은 자연수이다.
첫째 줄부터 N개의 줄에 오름차순으로 정렬한 결과를 한 줄에 하나씩 출력한다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
int[] cnt = new int[10001];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
for(int i=0; i<N; i++) {
cnt[Integer.parseInt(br.readLine())]++;
}
StringBuilder sb = new StringBuilder();
for(int i=1; i<10001; i++) {
while(cnt[i]>0) {
sb.append(i).append('\n');
cnt[i]--;
}
}
System.out.println(sb);
}
}