๋ณํฉ์ ๋ ฌ
๋ฐ์ดํฐ์ ์์๋ค์ ๋ ๊ทธ๋ฃน์ผ๋ก ๋๋ ํ ์ ๋ ฌํ๊ณ , ์ ๋ ฌ๋ ๋ ๊ทธ๋ฃน์ ๋น๊ตํ๋ฉฐ ํ๋๋ก ํฉ์น๋ ์๊ณ ๋ฆฌ์ฆ์ด๋ค.
๋ณํฉ์ ๋ ฌ๊ณผ์
#์ซ์ 8๊ฐ๋ฅผ ๋ฐ์ผ๋ก ๋๋๋ค
group1 = [2, 8, 4, 7]
group2 = [6, 1, 3, 5]
#๋ ๊ทธ๋ฃน์ ์ ๋ ฌํ๋ค.
group1 = [2, 4, 7, 8]
group2 = [1, 3, 5, 6]
#๋ ๊ทธ๋ฃน์ ํ๋์ ๊ทธ๋ฃน์ผ๋ก ํฉ์น๋ค.
๋ ๊ทธ๋ฃน์ ์ฒซ๋ฒ์งธ ๊ฐ์ ๋น๊ตํด ์์ ๊ฐ์ ์๋ก์ด ๋ฆฌ์คํธ(result)์ ๋ฃ๋๋ค.
group1 = [2, 4, 7, 8]
group2 = [3, 5, 6]
result = [1]
#๋ ๊ทธ๋ฃน์ ์ฒซ๋ฒ์งธ ๊ฐ์ ๋น๊ตํด ์์ ๊ฐ์ ์๋ก์ด ๋ฆฌ์คํธ์ ๋ฃ๋ ๊ฒ์ ๋ฐ๋ณตํ๋ค.
group1 = [4, 7, 8]
group2 = [3, 5, 6]
result = [1, 2]
group1 = [4, 7, 8]
group2 = [5, 6]
result = [1, 2, 3]
group1 = [7, 8]
group2 = [5, 6]
result = [1, 2, 3, 4]
group1 = [7, 8]
group2 = [6]
result = [1, 2, 3, 4, 5]
group1 = [7, 8]
group2 = []
result = [1, 2, 3, 4, 5, 6]
#group2์๋ ์๋ฃ๊ฐ ์์ผ๋ฏ๋ก group1์ ๋จ์์๋ ์๋ฃ๋ฅผ ๋ชจ๋ result๋ก ์ฎ๊ธด๋ค.
group1 = []
group2 = []
result = [1, 2, 3, 4, 5, 6, 7, 8]
๊ฒฐ๊ณผ : [1, 2, 3, 4, 5, 6, 7, 8]
๋ณํฉ์ ๋ ฌ ์๊ณ ๋ฆฌ์ฆ
def merge_sort(a):
n = len(a)
if n <= 1:
return
mid = n // 2
g1 = a[:mid]
g2 = a[mid:]
merge_sort(g1)
merge_sort(g2)
i = 0
j = 0
k = 0
while i < len(g1) and j < len(g2):
if g1[i] < g2[j]:
a[k] = g1[i]
i += 1
k += 1
else:
a[k] = g2[j]
j += 1
k += 1
while i < len(g1):
a[k] = g1[i]
i += 1
k += 1
while j < len(g2):
a[k] = g2[j]
j += 1
k += 1
d = [6, 8, 3, 9, 10, 1, 2, 4, 7, 5]
merge_sort(d)
print(d)
๋ ๋ค๋ฅธ ๋ฐฉ๋ฒ
def merge_sort(a):
n = len(a)
if n <= 1:
return a
mid = n // 2
g1 = merge_sort(a[:mid])
g2 = merge_sort(a[mid:])
result = []
while g1 and g2:
if g1[0] < g2[0]:
result.append(g1.pop(0))
else:
result.append(g2.pop(0))
while g1:
result.append(g1.pop(0))
while g2:
result.append(g2.pop(0))
return result
d = [6, 8, 3, 9, 10, 1, 2, 4, 7, 5]
print(merge_sort(d))
์ฐธ๊ณ
๋ณํฉ์ ๋ ฌ์ ์๊ฐ๋ณต์ก๋๋ O(N * logN)์ด๋ค.
'Algorithm > Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] ์ด๋ถ ํ์ (0) | 2020.08.26 |
---|---|
[Python] ํต ์ ๋ ฌ (0) | 2020.08.25 |
[Python] ์ฝ์ ์ ๋ ฌ (0) | 2020.08.22 |
[Python] ์ ํ์ ๋ ฌ (0) | 2020.08.20 |
[Python] ์์ฐจํ์ (0) | 2020.08.19 |