코딩테스트 연습 스터디 진행중 입니다. ✍✍✍
Notion : https://www.notion.so/1c911ca6572e4513bd8ed091aa508d67
문제
https://www.acmicpc.net/problem/23882
[나의 풀이]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static int selection_sort(int[] arr, int N, int K) {
int cnt = 0;
for (int i = N - 1; i > 0; i--) {
int max_idx = i;
for (int j = i - 1; j >= 0; j--) {
if (arr[j] >= arr[max_idx]) {
max_idx = j;
}
}
if (arr[i] == arr[max_idx]) {
continue;
}
cnt = swap(arr, i, max_idx, cnt);
// K번째 정렬일 때 출력
if (cnt == K) {
for (int el : arr) {
System.out.print(el + " ");
}
}
}
return cnt;
}
static int swap(int[] arr, int a, int b, int cnt) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
cnt++;
return cnt;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
int[] arr = new int[N];
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
int cnt = selection_sort(arr, N, K);
// 정렬횟수보다 K가 클 때는 -1
if (cnt < K) {
System.out.println(-1);
}
}
}
단순 선택 정렬 개념을 학습하고 관련한 문제를 풀어보았습니다! 크게 어렵지는 않았습니다!
감사합니다!🍎🍎🍎
👍