백준 10431 js

인지용·2024년 11월 3일
0

알고리즘

목록 보기
5/46
post-thumbnail

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


const input = require('fs')
    .readFileSync(process.platform === 'linux' ? '/dev/stdin' : './data.txt')
    .toString()
    .trim()
    .split('\n');


const P = input.shift();

for(let i=0; i<P; i++){
    let arr = input[i].split(" ").map(Number);
    const [T, result] = insertionSort(arr);

    console.log(T + " " + result)
}


//삽입 정렬
function insertionSort(arr) {
    let result = 0;
    const T = arr.shift();

    for(let j=1; j<arr.length; j++) {

        //비교하려는 기준 값
        const k = arr[j];

        //기준값 앞에 있는 요소
        let frontIndex=j-1;

        //앞요소가 현재값보다 큰 경우에만
        for(frontIndex; frontIndex>=0 && arr[frontIndex] > k; frontIndex--){
            //앞요소 뒤로 이동시킴
            arr[frontIndex+1] = arr[frontIndex];
            result++;
        }

      	//더 이상 앞으로 이동할 수 없는 경우
        //앞으로 계속 이동해온 현재 위치에 비교기준 값 할당
        arr[frontIndex+1] = k
    }

    return [T, result];
}

문제를 처음 봤을 때 정렬을 시키면서 카운트를 세면 될 것 같은데
무슨 방법이 있을까.. 고민하다가 정렬의 종류에 대하여 찾아봤고
그 중 앞에서부터 한칸씩 뒤로 옮기는 삽입 정렬을 알게 되었다.

첫 제출에서

반복문에 j<=arr.length;로 주니까
배열의 맨 마지막요소 인덱스는 19가 돼야 하는데 (0부터 카운트 하니까)
20이 되어서 배열 사이즈 초과로 에러가 났었다.

그리고 arr[frontIndex+1] = k 부분을 주지 않으니
제대로 값들 위치를 바꿔주지 않아 또 에러가 났었다.

아무튼 해결!

profile
한-줄

0개의 댓글