์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜7] ์„ ํƒ ์ •๋ ฌ (Javascript)

์€์ง„ 2021. 6. 27. 13:51

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜7] ์„ ํƒ ์ •๋ ฌ (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.


โœ๏ธIdea Sketch

2021-06-27

1. ์„ ํƒ ์ •๋ ฌ?

  • ์ฒซ๋ฒˆ์งธ ์›์†Œ์™€, ๋‚˜๋จธ์ง€ ์›์†Œ ์ค‘ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ๊ตํ™˜ํ•˜๋Š” ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜
  • ์ฒซ๋ฒˆ์งธ ์›์†Œ๋ถ€ํ„ฐ ๋งˆ์ง€๋ง‰๊นŒ์ง€ ๋ฐ˜๋ณต

2. for ๋ฐ˜๋ณต๋ฌธ 2๊ฐœ ์‚ฌ์šฉ

for (let i=0; i<arr.length; i++){
    for (let j=i+1; j<arr.length; j++) {
        if (arr[j] < min) [min, index] = [arr[j], j];
    }
    [arr[i], arr[index]] = [arr[index], arr[i]];
}

3. โ€ฆarr์„ ์“ด๋‹ค๋ฉด? arr.substr() ๋ณ‘ํ–‰

  • min ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ index๋„ ์•Œ์•„์•ผ ํ•˜๋ฏ€๋กœ ๋ถ€์ ์ ˆ

4. i++๋งˆ๋‹ค min๊ณผ index ์ดˆ๊ธฐํ™”


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-27

function solution(arr) {
    for (let i = 0; i < arr.length; i++) {
        let min = arr[i];
        let index = i;

        for (let j = i + 1; j < arr.length; j++) {
            if (arr[j] < min) [min, index] = [arr[j], j];
        }

        [arr[i], arr[index]] = [arr[index], arr[i]];
    }
    return arr;
}


  • min ๋ณ€์ˆ˜ ์—†์ด index ๋งŒ์œผ๋กœ๋„ ๊ตฌํ˜„๊ฐ€๋Šฅ
function solution(arr) {
    for (let i = 0; i < arr.length; i++) {
        let index = i;

        for (let j = i + 1; j < arr.length; j++) {
            if (arr[j] < arr[index]) index = j;
        }

        [arr[i], arr[index]] = [arr[index], arr[i]];
    }
    return arr;
}