์•Œ๊ณ ๋ฆฌ์ฆ˜

[Algorithm] ๋ณ‘ํ•ฉ ์ •๋ ฌ(merge sort)

jjingle 2024. 2. 6. 14:35

๋ณ‘ํ•ฉ ์ •๋ ฌ(merge sort) ?

  • ์žฌ๊ท€ ์šฉ๋ฒ•์„ ํ™œ์šฉํ•œ ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜
    1. ๋ฆฌ์ŠคํŠธ๋ฅผ ์ ˆ๋ฐ˜์œผ๋กœ ์ž˜๋ผ ๋น„์Šทํ•œ ํฌ๊ธฐ์˜ ๋‘ ๋ถ€๋ถ„ ๋ฆฌ์ŠคํŠธ๋กœ ๋‚˜๋ˆ”
    2. ๊ฐ ๋ถ€๋ถ„ ๋ฆฌ์ŠคํŠธ๋ฅผ ์žฌ๊ท€์ ์œผ๋กœ ํ•ฉ๋ณ‘ ์ •๋ ฌ์„ ์ด์šฉํ•ด ์ •๋ ฌ
    3. ๋‘ ๋ถ€๋ถ„ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋‹ค์‹œ ํ•˜๋‚˜์˜ ์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ๋กœ ํ•ฉ๋ณ‘

 

def merge(left, right):
  merged = list()
  left_point, right_point = 0,0
  
  #case1: left/right ๋‘˜๋‹ค ๋ฐ์ดํ„ฐ ์žˆ์„ ๋•Œ
  while len(left) > left_point and len(right) > right_point:
    it left[left_point] > right[right_point]:
      merged.append(right[right_point])
      right_point += 1
    else:
      merged.append(left[left_point])
      left_point += 1
  
  #case2: left ๋ฐ์ดํ„ฐ ์—†์„ ๋•Œ
  while len(left) > left_point:
    merged.append(left[left_point])
    left_point += 1
  
  #case3: right ๋ฐ์ดํ„ฐ ์—†์„ ๋•Œ
  while len(right) > right_point:
    merged.append(right[right_point])
    right_point += 1
    
  return merged
  
def mergesplit(data):
  if len(data) <= 1:
    return data
    
  medium = int(len(data) / 2)
  left = mergesplit(data[:medium])
  right = mergesplit(data[medium:])
  
  return merge(left,right)
  
  
#------------------------------------
import random

data_list = random.sample(range(100), 10)
mergesplit(data_list)