ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Algorithm] ์‚ฝ์ž…์ •๋ ฌ(Insertion Sort)
    ๐Ÿ’ปProgramming/Algorithm 2024. 3. 28. 18:22

    ์‚ฝ์ž…์ •๋ ฌ์ด๋ž€?

    ํ˜„์žฌ ๋น„๊ตํ•˜๊ณ ์ž ํ•˜๋Š” target๊ณผ ๊ทธ ์ด์ „์˜ ์›์†Œ๋“ค๊ณผ ๋น„๊ตํ•˜๋ฉฐ ์ž๋ฆฌ๋ฅผ ๊ตํ™˜(swap)ํ•˜๋Š” ์ •๋ ฌ ๋ฐฉ๋ฒ•.

    ์„ ํƒ์ •๋ ฌ, ๋ฒ„๋ธ”์ •๋ ฌ๊ณผ๋Š” ๋‹ค๋ฅด๊ฒŒ ์•ˆ์ • ์ •๋ ฌ.

     

    ์‚ฝ์ž…์ •๋ ฌ์˜ ๊ณผ์ •(์˜ค๋ฆ„์ฐจ์ˆœ ๊ธฐ์ค€)

    1. ์ธ๋ฑ์Šค 1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹ค. ํ˜„์žฌ ์ธ๋ฑ์Šค๋ฅผ ํƒ€๊ฒŸ ์ธ๋ฑ์Šค๋กœ ํ•˜๊ณ  ๋ณ€์ˆ˜์— ๋„ฃ๋Š”๋‹ค. ์ด ๋ณ€์ˆ˜๋ณด๋‹ค ์ด์ „ ์ธ๋ฑ์Šค๊ฐ€ ์ž‘์œผ๋ฉด ์ด์ „ ์ธ๋ฑ์Šค์˜ ๊ฐ’์„ ๊ทธ ๋‹ค์Œ ์ธ๋ฑ์Šค์— ๋„ฃ์–ด์ค€๋‹ค. 

    2. ๋งŒ์•ฝ์— ์ธ๋ฑ์Šค 2๊ฐ€ ํƒ€๊ฒŸ์ด๊ณ , ํƒ€๊ฒŸ์˜ ๊ฐ’์ด ์ธ๋ฑ์Šค 1๋ณด๋‹ค ์ž‘๋‹ค๋ฉด ๊ทธ ๋‹ค์Œ ์ธ๋ฑ์Šค์— ๋„ฃ๋Š”๋‹ค. ๋˜ ์ธ๋ฑ์Šค 0์ด ํƒ€๊ฒŸ๋ณด๋‹ค ์ž‘์œผ๋ฉด ๋˜ ๊ทธ ๋‹ค์Œ ์ธ๋ฑ์Šค์— ๋„ฃ๋Š”๋‹ค. ๊ทธ๋ฆฌ๊ณ  ํƒ€๊ฒŸ ์ธ๋ฑ์Šค์˜ ๊ฐ’์„ ์ธ๋ฑ์Šค 0์— ๋„ฃ์–ด์ค€๋‹ค.

    3. ์ด๋ฅผ ๊ณ„์† ๋ฐ˜๋ณตํ•œ๋‹ค. 

     

    ๊ตฌํ˜„ ์ฝ”๋“œ

    import java.util.Scanner;
    
    public class Main {
    
        private int[] solution(int n, int[] list) {
            int i, j;
            for (i = 1; i < n; i++) {
                int key = list[i];
                for (j = i - 1; j >= 0; j--) {
                    if (key < list[j])  list[j + 1] = list[j];
                    else    break;
                }
                list[j + 1] = key;
            }
    
            return list;
        }
    
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            Main T = new Main();
            int n = scanner.nextInt();
            int[] list = new int[n];
            for (int i = 0; i < n; i++) list[i] = scanner.nextInt();
            for (int i : T.solution(n, list)) System.out.print(i + " ");
        }
    }

     

    ์‚ฝ์ž…์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ์žฅ์ 

    • ์•ˆ์ •ํ•œ ์ •๋ ฌ ๋ฐฉ๋ฒ•
    • ๋ ˆ์ฝ”๋“œ ์ˆ˜๊ฐ€ ์ ์„ ๊ฒฝ์šฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ๊ฐ„๋‹จํ•˜๋ฏ€๋กœ ๋‹ค๋ฅธ ๋ณต์žกํ•œ ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜๋ณด๋‹ค ์œ ๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.
    • ์ด๋ฏธ ์ •๋ ฌ๋˜์–ด์žˆ๋Š” ๋ ˆ์ฝ”๋“œ์ผ ๊ฒฝ์šฐ ํšจ์œจ์ ์ผ ์ˆ˜ ์žˆ๋‹ค.

    ์‚ฝ์ž…์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ๋‹จ์ 

    • ๋งŽ์€ ๋ ˆ์ฝ”๋“œ๋“ค์˜ ์ด๋™์„ ํฌํ•จํ•œ๋‹ค. 
    • ๋ ˆ์ฝ”๋“œ ์ˆ˜๊ฐ€ ๋งŽ๊ณ  ํฌ๊ธฐ๊ฐ€ ํด ๊ฒฝ์šฐ์— ์ ํ•ฉํ•˜์ง€ ์•Š๋‹ค.

     

    ์‹œ๊ฐ„ ๋ณต์žก๋„

    ์ด๋ฏธ ๋ชจ๋“  ๋ ˆ์ฝ”๋“œ๊ฐ€ ์ •๋ ฌ๋˜์–ด ์žˆ๋Š” ๊ฒฝ์šฐ

    ๋น„๊ต ํšŸ์ˆ˜: ์ด๋™์ด ์—†์ด 1๋ฒˆ์˜ ๋น„๊ต๋งŒ ์ด๋ฃจ์–ด์ง„๋‹ค.

    ์™ธ๋ถ€ ๋ฃจํ”„: (n-1)๋ฒˆ -> O(n)

     

    ๋ ˆ์ฝ”๋“œ๊ฐ€ ์—ญ์ˆœ์œผ๋กœ ์ •๋ ฌ๋˜์–ด ์žˆ๋Š” ๊ฒฝ์šฐ

    ๋น„๊ต ํšŸ์ˆ˜: ์™ธ๋ถ€ ๋ฃจํ”„ ์•ˆ์˜ ๊ฐ ๋ฐ˜๋ณต๋งˆ๋‹ค i๋ฒˆ์˜ ๋น„๊ต๋ฅผ ์ˆ˜ํ–‰

    ์™ธ๋ถ€ ๋ฃจํ”„: (n-1)+(n-2)+...+2+1 = n(n-1)/2 = O(n^2)

     

     

    References

    https://gmlwjd9405.github.io/2018/05/06/algorithm-insertion-sort.html

     

    [์•Œ๊ณ ๋ฆฌ์ฆ˜] ์‚ฝ์ž… ์ •๋ ฌ(insertion sort)์ด๋ž€ - Heee's Development Blog

    Step by step goes a long way.

    gmlwjd9405.github.io

     

Designed by Tistory.