perry05

[백준] 2750 - 수 정렬하기(JAVA) 본문

문제풀이 기록/JAVA

[백준] 2750 - 수 정렬하기(JAVA)

perry05 2022. 12. 19. 15:27

[백준] 단계별로 풀어보기 - 정렬

https://www.acmicpc.net/problem/2750

 

2750번: 수 정렬하기

첫째 줄에 수의 개수 N(1 ≤ N ≤ 1,000)이 주어진다. 둘째 줄부터 N개의 줄에는 수가 주어진다. 이 수는 절댓값이 1,000보다 작거나 같은 정수이다. 수는 중복되지 않는다.

www.acmicpc.net

 

> 문제

> 풀이1 - 버블정렬

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
	public static void BubbleSort(int[] arr, int n) {
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < n-1; j++) {
				if(arr[j] > arr[j+1]) {
					int tmp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = tmp;
				}
			}
		}
	}
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		
		int n = Integer.parseInt(br.readLine());
		int[] arr = new int[n];
		
		for(int i = 0; i < n; i++) {
			arr[i] = Integer.parseInt(br.readLine());
		}
		br.close();
		
		BubbleSort(arr, n);
		
		for(int i = 0; i < n; i++) {
			sb.append(arr[i]).append("\n");
		}
		
		System.out.println(sb);
		
	}
}

> 풀이2 - 삽입정렬

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
	public static void InsertSort(int[] arr, int n) {
		int j;
		for(int i = 1; i < n; i++) {
			int tmp = arr[i];
			for(j = i-1; j >= 0 && arr[j] > tmp; j--) {
				arr[j+1] = arr[j];
			}
			arr[j+1] = tmp;
		}
	}
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		
		int n = Integer.parseInt(br.readLine());
		int[] arr = new int[n];
		
		for(int i = 0; i < n; i++) {
			arr[i] = Integer.parseInt(br.readLine());
		}
		br.close();
		
		InsertSort(arr, n);
		
		for(int i = 0; i < n; i++) {
			sb.append(arr[i]).append("\n");
		}
		
		System.out.println(sb);
		
	}
}

 

> 풀이3- 선택정렬

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Main {
	public static void SelectionSort(int[] arr, int n) {
		for(int i = 0; i < n-1; i++) {
			int minIndex = i;
			for(int j = i+1; j < n; j++) {
				if(arr[j] < arr[minIndex])
					minIndex = j;
			}
			int tmp = arr[minIndex];
			arr[minIndex] = arr[i];
			arr[i] = tmp;
		}
	}
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		
		int n = Integer.parseInt(br.readLine());
		int[] arr = new int[n];
		
		for(int i = 0; i < n; i++) {
			arr[i] = Integer.parseInt(br.readLine());
		}
		br.close();
		
		SelectionSort(arr, n);
		
		for(int i = 0; i < n; i++) {
			sb.append(arr[i]).append("\n");
		}
		
		System.out.println(sb);
		
	}
}

 

버블정렬, 삽입정렬, 선택정렬로 문제를 풀어보았다.

Comments