"Python 기수정렬 구현"의 두 판 사이의 차이

4번째 줄: 4번째 줄:


<source lang='python'>
<source lang='python'>
def radix_sort(a):
def radix_sort(a, base=10):
     def count_sort(a, exp):
     def counting_sort(a, exp, base):
     size = len(a)
     size = len(a)
     output = [0]*size
     output = [0]*size
     count = [0]*10
     count = [0]*base
     for i in range(size):
     for i in range(size):
     index = int(a[i]/exp)
     index = int(a[i]/exp)
     count[index%10] += 1
     count[index%base] += 1
     for i in range(1,10):
     for i in range(1,base): count[i]+=count[i-1]
    count[i] += count[i-1]
     for i in range(size-1,-1,-1):
     for i in range(size-1,-1,-1):
     index = int(a[i]/exp)
     index = int(a[i]/exp)
     output[count[index%10]-1] = a[i]
     output[count[index%base]-1] = a[i]
     count[index%10] -= 1
     count[index%base] -= 1
     for i in range(size):
     for i in range(size): a[i]=output[i]
    a[i] = output[i]
     maxval = max(a)
     maxval = max(a)
     exp = 1
     exp = 1
     while maxval/exp > 0:
     while maxval/exp > 0:
     count_sort(a, exp)
     counting_sort(a, exp, base)
     exp *= 10
     exp *= base
arr = [9,1,22,4,0,1,22,100,10]
arr = [9,1,22,4,0,1,22,100,10]
radix_sort( arr )
radix_sort( arr )

2018년 8월 27일 (월) 03:36 판

1 개요

Python 기수정렬 구현
파이썬 기수정렬 구현
def radix_sort(a, base=10):
    def counting_sort(a, exp, base):
    	size = len(a)
    	output = [0]*size
    	count = [0]*base
    	for i in range(size):
    		index = int(a[i]/exp)
    		count[index%base] += 1
    	for i in range(1,base): count[i]+=count[i-1]
    	for i in range(size-1,-1,-1):
    		index = int(a[i]/exp)
    		output[count[index%base]-1] = a[i]
    		count[index%base] -= 1
    	for i in range(size): a[i]=output[i]
    maxval = max(a)
    exp = 1
    while maxval/exp > 0:
    	counting_sort(a, exp, base)
    	exp *= base
arr = [9,1,22,4,0,1,22,100,10]
radix_sort( arr )
print( arr )
# [0, 1, 1, 4, 9, 10, 22, 22, 100]
def radix_sort(a, base=10):
    def list_to_buckets(a, base, iteration):
        buckets = [[] for x in range(base)]
        for x in a:
            digit = (x // (base ** iteration)) % base
            buckets[digit].append(x)
        return buckets
    def buckets_to_list(buckets):
        a = []
        for bucket in buckets:
            for x in bucket:
                a.append(x)
        return a
    maxval = max(a)
    it = 0
    while base ** it <= maxval:
        a = buckets_to_list(list_to_buckets(a, base, it))
        it += 1
    return a
arr = [9,1,22,4,0,1,22,100,10]
arr = radix_sort(arr)
print( arr )
# [0, 1, 1, 4, 9, 10, 22, 22, 100]

2 같이 보기

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