Ruby 계수정렬 구현

Jmnote (토론 | 기여)님의 2018년 8월 28일 (화) 02:05 판 (새 문서: ==개요== ;Ruby 계수정렬 구현 <source lang='ruby'> def counting_sort(a) count={} for x in a if not count.key?(x) then count[x]=1 else count[x]+=1 end...)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요

Ruby 계수정렬 구현
def counting_sort(a)
    count={}
    for x in a
        if not count.key?(x) then count[x]=1
        else count[x]+=1 end
    end
    pos = 0
    for x,repeat in count.sort_by {|k,v| k}
        a[pos...pos+repeat] = Array.new(repeat,x)
        pos += repeat
    end
end
arr = [9,1,22,4,0,-1,1,22,100,10]
counting_sort(arr)
print arr
# [-1, 0, 1, 1, 4, 9, 10, 22, 22, 100]

2 같이 보기

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