알고리즘/백준
[B2] 2750 : JAVA - 수 정렬하기
nagrang
2023. 8. 13. 01:36
https://www.acmicpc.net/problem/2750
2750번: 수 정렬하기
첫째 줄에 수의 개수 N(1 ≤ N ≤ 1,000)이 주어진다. 둘째 줄부터 N개의 줄에는 수가 주어진다. 이 수는 절댓값이 1,000보다 작거나 같은 정수이다. 수는 중복되지 않는다.
www.acmicpc.net
풀이
수의 개수가 1000개이고 시간 제한이 1초이므로 O(n^2)써도 충분한 문제이다. 그러므로 구현이 간단한 정렬 중 하나인 버블 정렬을 선택하여 풀었다.
입력
// 입력
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int [] nums = new int[N];
for(int i=0; i< N;i++){
nums[i] = sc.nextInt();
}
버블 정렬
// 버블 정렬
for(int i=N; i>=1; i--){
for(int j= 0; j< i-1; j++){
if(nums[j] > nums[j+1]){
int temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
출력
//출력
for(int i=0; i< N; i++){
System.out.println(nums[i]);
}
전체 코드
public class Main {
public static void main(String[] args) throws IOException {
// 입력
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int [] nums = new int[N];
for(int i=0; i< N;i++){
nums[i] = sc.nextInt();
}
// 버블 정렬
for(int i=N; i>=1; i--){
for(int j= 0; j< i-1; j++){
if(nums[j] > nums[j+1]){
int temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
//출력
for(int i=0; i< N; i++){
System.out.println(nums[i]);
}
}
}