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

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section07 - 1 - ์„ ํƒ์ •๋ ฌ

by YWTechIT 2021. 9. 7.
728x90

๐Ÿ“ section07 - 1 - ์„ ํƒ์ •๋ ฌ

์ด๋ฒˆ ์„น์…˜์€ ์ •๋ ฌ(sort), ๊ทธ๋ฆฌ๋””(greedy), ๊ฒฐ์ • ์•Œ๊ณ ๋ฆฌ์ฆ˜์— ๋Œ€ํ•ด์„œ ๋ฐฐ์šด๋‹ค.

 

๋ธ”๋กœ๊ทธ์— ๋”ฐ๋กœ ๊ฒŒ์‹œํ•˜์ง„ ์•Š์•˜์ง€๋งŒ ์ด์ „์— ์ข…์ข… ์‚ฝ์ž…์ •๋ ฌ, ์„ ํƒ์ •๋ ฌ, ๋ณ‘ํ•ฉ์ •๋ ฌ, ๋ฒ„๋ธ”์ •๋ ฌ, ํ€ต์ •๋ ฌ ์ฝ”๋“œ ๊ตฌํ˜„๊นŒ์ง€ ๊ณต๋ถ€ํ–ˆ๋Š”๋ฐ, ํ•ญ์ƒ ์ •๋ ฌ ๋ฌธ์ œ๋ฅผ ํ’€ ๋•Œ๋งˆ๋‹ค ์•Œ๋งž์€ ์ •๋ ฌ ์ฝ”๋“œ๋ฅผ ๊ตฌํ˜„ํ•˜๋ ค๊ณ  ํ•˜๋ฉด ๊นŒ๋จน๋Š”๋‹ค. ๐Ÿ˜… ๐Ÿ˜… ์ด๋ฒˆ ์„น์…˜์„ ํ’€๋ฉด์„œ ์–ธ์ œ ์–ด๋–ค ์ •๋ ฌ์„ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋Š”์ง€ ์ž˜ ์•Œ์•„๋‘ฌ์•ผ๊ฒ ๋‹ค. ์„ ํƒ ์ •๋ ฌ์— ๊ด€ํ•œ ์งง์€ ์˜์ƒ์€ ์„ ํƒ์ •๋ ฌ 5๋ถ„๋งŒ์— ์ดํ•ดํ•˜๊ธฐ - ์ฝ”๋”ฉํ•˜๋Š”๊ฑฐ๋‹ˆ ๊ฐœ์ธ์ ์œผ๋กœ ์ด ๋ถ„ ์˜์ƒ์ด ๊ธธ์ง€ ์•Š๊ณ  ํ•ต์‹ฌ๋งŒ ๊ฐ€๋ฅด์ณ์ฃผ๋Š” ์˜์ƒ์ด์–ด์„œ ์ข‹์•˜๋‹ค.

 

์„ ํƒ ์ •๋ ฌ์€ ๊ฐ€์žฅ ์ž‘์€ ์ˆซ์ž๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ํƒ์ƒ‰ํ•˜์—ฌ ๊ฐ€์žฅ ์™ผ์ชฝ ์ž๋ฆฌ๋ถ€ํ„ฐ swap ํ•˜๋Š” ์ •๋ ฌ์ด๋‹ค. ์ด์ค‘ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ์ „์ฒด ์›์†Œ๋ฅผ ํƒ์ƒ‰ํ•˜๊ณ  ๋‚˜๋ณด๋‹ค ์ž‘์€ ๊ฐ’์ด ์žˆ์œผ๋ฉด ๋‘ ๊ฐœ์˜ ์œ„์น˜๋ฅผ ์„œ๋กœ ๋ฐ”๊พธ๋Š” ์ •๋ ฌ์ด๋‹ค. ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(N^2)์ด๊ณ , ์ตœ์ ์˜ ๊ฒฝ์šฐ(์ •๋ ฌ๋˜์–ด์žˆ๋Š” ๊ฒฝ์šฐ)์—๋„ ์ƒ๊ด€์—†์ด ์›์†Œ๋ฅผ ๋ชจ๋‘ ๋น„๊ตํ•˜๋ฏ€๋กœ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ O(N^2)์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค.

 

(์ถœ์ฒ˜: VisuAlgo)

 

 

728x90

 

// ๋‚˜์˜ ์ฝ”๋“œ(j๋ฒˆ ๋ชจ๋‘ ๋ฐ”๊พธ๋Š” ๋ฐฉ๋ฒ•)
let n = 6;
let arr = [6, 5, 4, 3, 2, 1];

console.log(solution(n, arr));

function solution(n, arr) {
  for (let i=0; i<n-1; i++) {
    for (let j=i+1; j<n; j++) {
      if (arr[i]>arr[j]) {
        let temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
      }
    }
  }
  return arr;
}

 

// ๊ฐ•์˜ ์ฝ”๋“œ(j๋ฒˆ ์•ˆ์—์„œ idx๋ฅผ ๊ฐฑ์‹ ํ•˜์—ฌ ํ•œ๋ฒˆ์— ๋ฐ”๊พธ๋Š” ๋ฐฉ๋ฒ•)
let n = 6;
let arr = [6, 5, 4, 3, 2, 1];

console.log(solution(n, arr));

function solution(n, arr) {
    for (let i=0; i<n-1; i++) {
        let idx=i;
        for (let j=i+1; j<n; j++) {
            if (arr[i] > arr[j]) idx = i;
        }
        [arr[i], arr[idx]] = [arr[idx], arr[i]];
    }
    return arr;
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€