๋ณํฉ ์ ๋ ฌ(merge sort) ?
- ์ฌ๊ท ์ฉ๋ฒ์ ํ์ฉํ ์ ๋ ฌ ์๊ณ ๋ฆฌ์ฆ
- ๋ฆฌ์คํธ๋ฅผ ์ ๋ฐ์ผ๋ก ์๋ผ ๋น์ทํ ํฌ๊ธฐ์ ๋ ๋ถ๋ถ ๋ฆฌ์คํธ๋ก ๋๋
- ๊ฐ ๋ถ๋ถ ๋ฆฌ์คํธ๋ฅผ ์ฌ๊ท์ ์ผ๋ก ํฉ๋ณ ์ ๋ ฌ์ ์ด์ฉํด ์ ๋ ฌ
- ๋ ๋ถ๋ถ ๋ฆฌ์คํธ๋ฅผ ๋ค์ ํ๋์ ์ ๋ ฌ๋ ๋ฆฌ์คํธ๋ก ํฉ๋ณ
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)
'์๊ณ ๋ฆฌ์ฆ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Algorithm] ์์ฐจ ํ์ (Sequential Search) (0) | 2024.02.07 |
---|---|
[Algorithm] ์ด์ง ํ์ (Binary Search) (0) | 2024.02.06 |
[Algorithm] ํต ์ ๋ ฌ(Quick Sort) (0) | 2024.02.05 |
๋์ ๊ณํ๋ฒ( Dynamic Programming) ๊ณผ ๋ถํ ์ ๋ณต(Divide Conquer) (0) | 2024.02.05 |
[Algorithm] ์ฌ๊ท ์ฉ๋ฒ (recursive call, ์ฌ๊ท ํธ์ถ) (0) | 2024.01.30 |