3.1. Sorting - 3.1.3 Insertion Sort

2024. 1. 15. 20:58ใ†CS - Roadmap.sh/3. Common Algorithms

CS - 3. Common Algorithms - 3.1. Sorting - 3.1.3 Insertion Sort

 

๐Ÿ’กInsertion sort is a simple sorting algorithm that builds the final sorted array one item at a time by comparisons. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.

์‚ฝ์ž… ์ •๋ ฌ์€ ๋น„๊ต๋ฅผ ํ†ตํ•ด ํ•œ ๋ฒˆ์— ํ•œ ํ•ญ๋ชฉ์”ฉ ์ตœ์ข… ์ •๋ ฌ๋œ ๋ฐฐ์—ด์„ ๊ตฌ์ถ•ํ•˜๋Š” ๊ฐ„๋‹จํ•œ ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ž…๋‹ˆ๋‹ค. ํ€ต ์ •๋ ฌ, ํž™ ์ •๋ ฌ ๋˜๋Š” ๋ณ‘ํ•ฉ ์ •๋ ฌ๊ณผ ๊ฐ™์€ ๊ณ ๊ธ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜์— ๋น„ํ•ด ํฐ ๋ชฉ๋ก์—์„œ๋Š” ํšจ์œจ์„ฑ์ด ํ›จ์”ฌ ๋–จ์–ด์ง‘๋‹ˆ๋‹ค.

 

์‚ฝ์ž… ์ •๋ ฌ(Insertion Sort)๋Š” ๊ฐ ์ˆซ์ž๋ฅผ ์ ์ ˆํ•œ ์œ„์น˜์— '์‚ฝ์ž…'ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ์ •๋ ฌํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ž…๋‹ˆ๋‹ค.

์ฃผ์–ด์ง„ ๋ฐฐ์—ด์„ ๋‘ ๋ถ€๋ถ„์œผ๋กœ ๋‚˜๋ˆ„์–ด, ํ•˜๋‚˜๋Š” ์ด๋ฏธ ์ •๋ ฌ๋œ ๋ถ€๋ถ„์ด๊ณ  ๋‹ค๋ฅธ ํ•˜๋‚˜๋Š” ์•„์ง ์ •๋ ฌ๋˜์ง€ ์•Š์€ ๋ถ€๋ถ„์œผ๋กœ ๊ฐ„์ฃผํ•ฉ๋‹ˆ๋‹ค.

 

์‚ฝ์ž… ์ •๋ ฌ์˜ ๋™์ž‘ ๊ณผ์ •์€ ์ด๋ ‡์Šต๋‹ˆ๋‹ค.

1. ๋ฐฐ์—ด์˜ ์ฒซ ๋ฒˆ์จฐ ์›์†Œ๋Š” ์ด๋ฏธ ์ •๋ ฌ๋œ ๊ฒƒ์œผ๋กœ ๊ฐ„์ฃผํ•ฉ๋‹ˆ๋‹ค.

2. ์ •๋ ฌ๋˜์ง€ ์•Š์€ ๋ถ€๋ถ„์˜ ์ฒซ ๋ฒˆ ์จฐ ์›์†Œ๋ฅผ ์„ ํƒํ•˜๊ณ , ์ด๋ฏธ ์ •๋ ฌ๋œ ๋ถ€๋ถ„์—์„œ ์ด ์›์†Œ๋ณด๋‹ค ํฐ ์›์†Œ๋“ค์„ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ํ•œ์นธ ์”ฉ ์ด๋™์‹œํ‚ต๋‹ˆ๋‹ค.

3. ์ด๋ ‡๊ฒŒ ํ•ด์„œ ๋นˆ ์ž๋ฆฌ๊ฐ€ ์ƒ๊ธฐ๋ฉด, ์„ ํƒํ•œ ์›์†Œ๋ฅผ ๊ทธ ์ž๋ฆฌ์— ์‚ฝ์ž…ํ•ฉ๋‹ˆ๋‹ค.

4. ์ด ๊ณผ์ •์„ ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์›์†Œ๊ฐ€ ์ •๋ ฌ๋  ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.

 

In Python
def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i-1
        while j >= 0 and key < arr[j]:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
    return arr

 

์‚ฝ์ž… ์ •๋ ฌ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” ์ตœ์•…์˜ ๊ฒฝ์šฐ O(n^2)์ž…๋‹ˆ๋‹ค. 

์ด๋ฏธ ๊ฑฐ์˜ ์ •๋ ฌ๋œ ๋ฐฐ์—ด์—์„œ ๋งค์šฐ ํšจ์œจ์ ์œผ๋กœ ๋™์ž‘ํ•˜๋ฉฐ, ์ด ๊ฒฝ์šฐ์—๋Š” ๊ฑฐ์˜ O(n)์— ๊ฐ€๊นŒ์šด ์„ฑ๋Šฅ์„ ๋ณด์—ฌ์ค๋‹ˆ๋‹ค.

์™œ ๊ทธ๋Ÿด๊นŒ์š”?

๋ฐฐ์—ด์ด ์ด๋ฏธ ๊ฑฐ์˜ ์ •๋ ฌ๋œ ์ƒํƒœ๋ผ๋ฉด, ๊ฐ ์›์†Œ๋ฅผ ์ ์ ˆํ•œ ์œ„์น˜์— ์‚ฝ์ž…ํ•˜๋Š”๋ฐ ํ•„์š”ํ•œ ๋น„๊ต ํšŸ์ˆ˜๊ฐ€ ๋งค์šฐ ์ ์–ด์ง‘๋‹ˆ๋‹ค.

์ •ํ™•ํ•˜๊ฒŒ ์ดํ•ดํ•˜๋ ค๋ฉด, ์‚ฝ์ž… ์ •๋ ฌ์˜ ๋™์ž‘ ๋ฐฉ์‹์„ ์ƒ๊ฐํ•ด๋ณด๋ฉด ๋ฉ๋‹ˆ๋‹ค.

๋Œ€๋ถ€๋ถ„์˜ ์›์†Œ๊ฐ€ ์ด๋ฏธ ์ ์ ˆํ•œ ์œ„์น˜์— ์žˆ์œผ๋ฏ€๋กœ, ์‚ฝ์ž…ํ•  ์œ„์น˜๋ฅผ ์ฐพ๊ธฐ ์œ„ํ•œ ๋น„๊ต์ˆ˜๊ฐ€ ํ›จ์”ฌ ์ ์–ด O(n)์— ๊ฐ€๊นŒ์›Œ์ง„๋‹ค๋Š” ๊ฒƒ.

728x90

'CS - Roadmap.sh > 3. Common Algorithms' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

3.1. Sorting - 3.1.6 Merge Sort  (0) 2024.01.20
3.1 Sorting - 3.1.5 Quick Sort  (0) 2024.01.16
3.1 Sorting - 3.1.4 Heap Sort  (0) 2024.01.15
3.1. Sorting - 3.1.2 Selection Sort  (1) 2024.01.14
3.1. Sorting - 3.1.1 Bubble sort  (1) 2024.01.13