본문 바로가기
Beakjoon&프로그래머스/Java

[백준/Java] 24052번 알고리즘 수업 - 삽입 정렬 2

by 현장 2026. 1. 4.

-Code

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class BOJ24052 {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int len = Integer.parseInt(st.nextToken());
        int changeCnt = Integer.parseInt(st.nextToken());
        // nums 초기화
        int[] nums = new int[len];
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < len; i++) {
            nums[i] = Integer.parseInt(st.nextToken());
        }
        // 삽입 정렬
        int[] ansArr = insertSort(nums, len, changeCnt);
        // 출력
        if (ansArr == null) {
            System.out.println(-1);
        } else {
            for (int num : ansArr) {
                System.out.print(num + " ");
            }
        }
    }

    private static int[] insertSort(int[] nums, int len, int changeCnt) {
        int cnt = 0;

        for (int i = 1; i < len; i++) {
            int location = i - 1;
            int newItem = nums[i];
            // 현재 아이템이 작을 경우 location위치의 값을 뒤로 밀음
            while (0 <= location && newItem < nums[location]) {
                nums[location + 1] = nums[location];
                // 변경이 일어날때 마다 cnt 증가 후 검사
                if (++cnt == changeCnt) return nums.clone();
                location--;
            }
            // 위치 변경이 일어난 경우 현재 아이템을 맞는 위치에 넣음
            // 이것도 변경이므로 cnt 증가 후 비교 로직
            if (location + 1 != i) {
                nums[location + 1] = newItem;
                if (++cnt == changeCnt) return nums.clone();
            }

        }
        return null;
    }
}

마지막 변경이 발생한 이후에는 현재 저장해 둔 아이템을 자리에 넣어줘야 하는 곳에도 cnt를 증가 후 체크하는 로직이 추가되어야 하는데 그 부분도 포함인 줄 몰라서 처음에 틀렸었습니다.