๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/์ธํ”„๋Ÿฐ(inflearn)

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section05 - 1 - ๋‘ ๋ฐฐ์—ด ํ•ฉ์น˜๊ธฐ

by YWTechIT 2021. 8. 23.
728x90

๐Ÿ“ section05 - 1 - ๋‘ ๋ฐฐ์—ด ํ•ฉ์น˜๊ธฐ

์ด๋ฒˆ ์„น์…˜์€ ํšจ์œจ์„ฑ์„ ๊ณ ๋ คํ•˜๋Š” ์„น์…˜์œผ๋กœ ํˆฌ ํฌ์ธํ„ฐ, ์Šฌ๋ผ์ด๋”ฉ์œˆ๋„์šฐ, ํ•ด์‰ฌ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋ณธ๋‹ค.

 

์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋œ ๋ฐฐ์—ด์„ ํ•ฉ์น˜๋Š” ๋ฌธ์ œ์ธ๋ฐ, ์ €๋ฒˆ์— ๋ณ‘ํ•ฉ ์ •๋ ฌ(mergeSort) ์—ฐ์Šตํ•˜๋‹ค๊ฐ€ ์ด ๋ฌธ์ œ์™€ ๋น„์Šทํ•œ ๋กœ์ง์ธ ๊ฒƒ ๊ฐ™์•„์„œ ๊ทธ๋Œ€๋กœ ์ ์šฉํ–ˆ๋‹ค. ๊ฐ•์‚ฌ๋‹˜ ์ฝ”๋“œ๋Š” ๋‚˜์˜ ์ฝ”๋“œ์™€ ์กฐ๊ธˆ ๋น„์Šทํ•˜๋ฉด์„œ ๋‹ฌ๋ž๋‹ค. ๋˜, ๋ฌธ์ œ์—์„œ n์˜ ๋ฒ”์œ„๊ฐ€ 100๊นŒ์ง€๊ธฐ ๋•Œ๋ฌธ์— ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๋‹คํ•ญ์‹œ๊ฐ„(O(N^2) ์ด์ƒ)๋‚ด๋กœ ํ’€์–ด๋„ ๋˜์ง€๋งŒ, ๋ฒ”์œ„๊ฐ€ ํฐ ๊ฒฝ์šฐ๋ฅผ ๋Œ€๋น„ํ•ด์„œ TwoPointer๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ O(N)์œผ๋กœ ํ’€์—ˆ๋‹ค. ๋˜‘๊ฐ™์ด ํ’€ ์ˆ˜ ์žˆ๋Š”๋ฐ ์™œ twoPointer๋ฅผ ์„ ํƒํ–ˆ๋ƒ๊ณ  ๋ฌป๋Š”๋‹ค๋ฉด ๋งŒ์•ฝ, ์‹ค๋ฌด์—์„œ O(N^2) ์ฝ”๋“œ์™€ O(N)์ฝ”๋“œ๊ฐ€ ์žˆ์„ ๋•Œ O(N)์ฝ”๋“œ๋ฅผ ์„ ํƒํ•  ๊ฒƒ์ž„์€ ์ž๋ช…ํ•˜๋‹ค.

 

๊ฐ•์‚ฌ๋‹˜์€ ํ›„์น˜์—ฐ์‚ฐ์ž(postfix form)๋ฅผ ์‚ฌ์šฉํ•˜์…จ๋Š”๋ฐ, ํ›„์น˜์—ฐ์‚ฐ์ž์˜ ํŠน์ง•์€ ์—ฐ์‚ฐ์ž๊ฐ€ ๋ณ€์ˆ˜ ๋’ค์— ์˜ฌ ๋•Œ ๊ฐ’์„ ๋จผ์ € ๊ณ„์‚ฐํ•˜๊ณ  ์ฆ๊ฐ€/๊ฐ์†Œ๊ฐ€ ์ด๋ฃจ์–ด์ง€๋Š” ํ˜•ํƒœ๋‹ค. ์ฝ”๋“œ๋ฅผ ๊ฐ„๋žตํ•˜๊ฒŒ ์“ธ ๋•Œ ์ข‹์€๊ฒƒ ๊ฐ™๋‹ค. ๋˜ while๋ฌธ์˜ ์กฐ๊ฑด์„ &&๋กœ ํ•ด์ค˜์•ผ ๋‘˜ ์ค‘ ํ•˜๋‚˜๊ฐ€ false ์ผ ๋•Œ ์ „์ฒด ๋ฐ˜๋ณต๋ฌธ์ด false๊ฐ€ ๋˜๋Š”๊ฒƒ๋„ ์žŠ์ง€ ๋ง์ž.

 

// ๋‚˜์˜์ฝ”๋“œ
let n = 4;
let arr1 = [1, 10, 20, 50];
let m = 5;
let arr2 = [3, 6, 10, 20, 25];

console.log(solution(n, arr1, m, arr2));

function solution(n, nArr, m, mArr) {
  let p1 = p2 = 0;
  let answer = [];

  while (n<p1 && m<p2) {
    if (nArr[p1] < mArr[p1]) {
      answer.push(nArr[p1]);
      p1++;
    } else {
      answer.push(mArr[p2]);
      p2++;
    }
  }

  return answer.concat(nArr.slice(p1), mArr.slice(p2));
}

 

// ๊ฐ•์‚ฌ๋‹˜ ์ฝ”๋“œ
let n = 4;
let arr1 = [1, 10, 20, 50];
let m = 5;
let arr2 = [3, 6, 10, 20, 25];

console.log(solution(n, arr1, m, arr2));

function solution(n, arr1, m, arr2){
    let p1 = p2 = 0;
    let answer = [];

    while (p1<n && p2<m){
        if (arr1[p1] < arr2[p2]) answer.push(arr1[p1++]);
        else answer.push(arr2[p2++]);
    }

    while (p1<n) answer.push(arr1[p1++]);
    while (p2<m) answer.push(arr2[p2++]);

    return answer;
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€