3.1. Sorting - 3.1.2 Selection Sort

2024. 1. 14. 21:43ใ†CS - Roadmap.sh/3. Common Algorithms

CS - 3. Common Algorithms - 3.1. Sorting - 3.1.2 Selection Sort

 

๐Ÿ’ก Selection sort is a sorting algorithm that selects the smallest unsorted item in the list and swaps it with index 0, then finds the next smallest and places it into index 1 and so on.

์„ ํƒ ์ •๋ ฌ์€ ๋ชฉ๋ก์—์„œ ์ •๋ ฌ๋˜์ง€ ์•Š์€ ๊ฐ€์žฅ ์ž‘์€ ํ•ญ๋ชฉ์„ ์„ ํƒํ•˜์—ฌ ์ธ๋ฑ์Šค 0์œผ๋กœ ๋ฐ”๊พผ ๋‹ค์Œ ๋‹ค์Œ์œผ๋กœ ์ž‘์€ ํ•ญ๋ชฉ์„ ์ฐพ์•„์„œ ์ธ๋ฑ์Šค 1์— ๋ฐฐ์น˜ํ•˜๋Š” ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ž…๋‹ˆ๋‹ค.

 

์„ ํƒ ์ •๋ ฌ(Selection Sort)์€ ์ด๋ฆ„์—์„œ ์•Œ ์ˆ˜ ์žˆ๋“ฏ์ด, ๊ฐ€์žฅ ์ ์€ ๊ฐ’์„ ์„ ํƒํ•˜์—ฌ ์•ž์œผ๋กœ ์˜ฎ๊ธฐ๋Š” ๋ฐฉ์‹์œผ๋กœ ์ •๋ ฌํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ž…๋‹ˆ๋‹ค.

์„ ํƒ ์ •๋ ฌ์˜ ๋™์ž‘ ๊ณผ์ •์€ ์ด๋Ÿฐ ์ˆœ์ž…๋‹ˆ๋‹ค.

1. ์ฃผ์–ด์ง„ ๋ฆฌ์ŠคํŠธ ์ค‘์—์„œ ์ตœ์†Œ๊ฐ’์„ ์ฐพ์Šต๋‹ˆ๋‹ค.

2. ๊ทธ ๊ฐ’์„ ๋ฆฌ์ŠคํŠธ์˜ ๋งจ ์•ž์— ์œ„์น˜ํ•œ ๊ฐ’๊ณผ ๊ต์ฒดํ•ฉ๋‹ˆ๋‹ค.

3. ๋งจ ์ฒ˜์Œ ์œ„์น˜๋ฅผ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋Œ€์ƒ์œผ๋กœ ์œ„์˜ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.

4. ์ด ๊ณผ์ •์ด ๋๋‚˜๋ฉด ๋ฆฌ์ŠคํŠธ๋Š” ์ •๋ ฌ๋œ ์ƒํƒœ๊ฐ€ ๋ฉ๋‹ˆ๋‹ค.

 

In Python
def selection_sort(arr):
    for i in range(len(arr)):
        min_idx = i
        for j in range(i+1, len(arr)):
            if arr[j] < arr[min_idx]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr

 

์„ ํƒ ์ •๋ ฌ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(n^2)๋กœ, ๋ฒ„๋ธ” ์ •๋ ฌ๊ณผ ๋™์ผํ•˜๊ฒŒ ๋ฐ์ดํ„ฐ์˜ ์–‘์ด ๋งŽ์ง€ ์•Š์€ ๊ฒฝ์šฐ์— ํšจ๊ณผ์ ์ž…๋‹ˆ๋‹ค.

ํ•˜์ง€๋งŒ, ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ๋ฐ์ดํ„ฐ์˜ ์–‘์ด ๋งŽ๊ฑฐ๋‚˜ ๋ฌด์ž‘์œ„๋กœ ๋ฐฐ์—ด๋œ ํ€ต ์ •๋ ฌ, ๋ณ‘ํ•ฉ ์ •๋ ฌ ๋“ฑ์ด ๋” ํšจ์œจ์ ์ธ ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜๋Š”๊ฒƒ์ด ์ข‹๋‹ค!

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.3 Insertion Sort  (0) 2024.01.15
3.1. Sorting - 3.1.1 Bubble sort  (1) 2024.01.13