์•Œ๊ณ ๋ฆฌ์ฆ˜

[Algorithm] ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ (Sort Algorithm)

jjingle 2024. 1. 30. 16:29

์ •๋ ฌ (Sorting) ?

- ์–ด๋–ค ๋ฐ์ดํ„ฐ๋“ค์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ด๋ฅผ ์ •ํ•ด์ง„ ์ˆœ์„œ๋Œ€๋กœ ๋‚˜์—ดํ•˜๋Š” ๊ฒƒ
- ์ •๋ ฌ์€ ํ”„๋กœ๊ทธ๋žจ ์ž‘์„ฑ ์‹œ, ๋นˆ๋ฒˆํ•˜๊ฒŒ ํ•„์š”
- ๋‹ค์–‘ํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ๊ณ ์•ˆ๋˜์—ˆ์œผ๋ฉฐ, ์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ•™์Šต์˜ ํ•„์ˆ˜

 

 

๋ฒ„๋ธ” ์ •๋ ฌ(bubble sort)

: ๋‘ ์ธ์ ‘ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๋น„๊ตํ•ด์„œ, ์•ž์—์žˆ๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ๋’ค์—์žˆ๋Š” ๋ฐ์ดํ„ฐ๋ณด๋‹ค ํฌ๋ฉด ์ž๋ฆฌ๋ฅผ ๋ฐ”๊ฟˆ

 

def bubblesort(data):
  for index in range(len(data) - 1 ):
    swap = False
        
    for index2 in range(len(data) - index - 1):
      if data[index2] > data[index2 + 1]:
        data[index2], data[index2 + 1] = data[index2 + 1], data[index2]
        swap = True
                
        if swap == False:
           break
            
  return data

 

 

์‚ฝ์ž… ์ •๋ ฌ(insertion sort)

  • ์‚ฝ์ž… ์ •๋ ฌ์€ ๋‘ ๋ฒˆ์งธ ์ธ๋ฑ์Šค๋ถ€ํ„ฐ ์‹œ์ž‘
  • ํ•ด๋‹น ์ธ๋ฑ์Šค(key ๊ฐ’) ์•ž์— ์žˆ๋Š” ๋ฐ์ดํ„ฐ(B) ๋ถ€ํ„ฐ ๋น„๊ตํ•ด์„œ key๊ฐ’์ด ๋” ์ž‘์œผ๋ฉด, B๊ฐ’์„ ๋’ค ์ธ๋ฑ์Šค๋กœ ๋ณต์‚ฌ
  • ์ด๋ฅผ key๊ฐ’์ด ๋” ํฐ ๋ฐ์ดํ„ฐ๋ฅผ ๋งŒ๋‚  ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต, ๊ทธ๋ฆฌ๊ณ  ํฐ ๋ฐ์ดํ„ฐ๋ฅผ ๋งŒ๋‚œ ์œ„์น˜ ๋ฐ”๋กœ ๋’ค์— key๊ฐ’์„ ์ด๋™
def insertion_sort(data):
  for index in range(len(data) - 1 ):
    for index2 in range(index + 1, 0, -1):
      if data[index2] < data[index2 - 1]:
        data[index2], data[index2 - 1] = data[index2 - 1], data[index2]
      else:
        break
  return data

 

 

์„ ํƒ ์ •๋ ฌ(selection sort)

 :  ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ˆœ์„œ๋ฅผ ๋ฐ˜๋ณตํ•˜๋ฉฐ ์ •๋ ฌํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜

  1. ์ฃผ์–ด์ง„ ๋ฐ์ดํ„ฐ ์ค‘, ์ตœ์†Œ๊ฐ’์„ ์ฐพ์Œ
  2. ํ•ด๋‹น ์ตœ์†Œ๊ฐ’์„ ๋ฐ์ดํ„ฐ ๋งจ ์•ž์— ์œ„์น˜ํ•œ ๊ฐ’๊ณผ ๊ต์ฒด
  3. ๋งจ ์•ž์˜ ์œ„์น˜๋ฅผ ๋บ€ ๋‚˜๋จธ์ง€ ๋ฐ์ดํ„ฐ๋ฅผ ๋™์ผํ•œ ๋ฐฉ๋ฒ•์œผ๋กœ ๋ฐ˜๋ณต
def selection_sort(data):
  for stand in range(len(data) - 1):
    lowest = stand

    for index in range(stand + 1, len(data)):
      if data[lowest] > data[index]:
        lowest = index

    data[lowest], data[stand] = data[stand], data[lowest]
  return data