Python 병합정렬 구현

1 개요[편집]

Python 병합정렬 구현
def merge_sort(a, left=0, right=-1):
    def merge(a, left, middle, right):
    	n1 = middle + 1 - left 
    	n2 = right - middle
    	L = [0] * (n1)
    	R = [0] * (n2)
    	for i in range(0, n1): L[i]=a[left+i]
    	for j in range(0, n2): R[j]=a[middle+1+j]
    	i = j = 0
    	k = left
    	while i<n1 and j<n2:
    		if L[i]<=R[j]: a[k]=L[i]; i+=1; k+=1
    		else: a[k]=R[j]; j+=1; k+=1
    	while i<n1: a[k]=L[i]; i+=1; k+=1
    	while j<n2:	a[k]=R[j]; j+=1; k+=1
    if right==-1: right=len(a)-1
    if left>=right: return
    middle = (left+right-1)//2
    merge_sort(a, left, middle)
    merge_sort(a, middle+1, right)
    merge(a, left, middle, right)
arr = [9,1,22,4,0,-1,1,22,100,10]
merge_sort(arr)
print( arr )
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100]

2 같이 보기[편집]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}