728x90
문제
N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오.
입력
첫째 줄에 수의 개수 N(1 ≤ N ≤ 1,000)이 주어진다. 둘째 줄부터 N개의 줄에는 수 주어진다. 이 수는 절댓값이 1,000보다 작거나 같은 정수이다. 수는 중복되지 않는다.
출력
첫째 줄부터 N개의 줄에 오름차순으로 정렬한 결과를 한 줄에 하나씩 출력한다.
선택 정렬로 result 배열을 새로 만들어 정렬하였다.
이중 for loop를 돌며 가장 작은 원소를 맨 앞으로 두는 과정을 반복한다.
시간 복잡도는 O(n^2)로, 상대적으로 비효율적인 알고리즘이다.
package BOJ0726;
import java.util.Scanner;
public class BOJ_2750_수정렬 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = sc.nextInt();
}
int[] result = new int[N];
// 선택 정렬
for (int i = 0; i < N; i++) {
int min = i;
for (int j = i + 1; j < N; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
result[i] = arr[min];
arr[min] = arr[i];
// swap
}
for (int num : result) {
System.out.println(num);
}
}
}
728x90
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 1316 - 그룹 단어 체커 (자바/Java) (0) | 2022.07.26 |
---|---|
[백준] 10989 - 수 정렬하기 3 (자바/Java) : 계수 정렬(Counting Sort) (0) | 2022.07.26 |
[백준] 11651 - 좌표 정렬하기 2 (자바/Java) : Merge Sort (0) | 2022.07.26 |
[백준] 1427 - 소트인사이드 (자바/Java) : 계수 정렬(Counting Sort) (0) | 2022.07.26 |
[백준] 2751 - 수 정렬하기2 (자바/JAVA): 합병 정렬(Merge Sort) (0) | 2022.07.26 |