1 ๋ถ„ ์†Œ์š”

Counting_Sort (๊ณ„์ˆ˜ ์ •๋ ฌ)

1. ๊ณ„์ˆ˜ ์ •๋ ฌ์ด๋ž€?

์ฃผ์–ด์ง„ ๋ฐฐ์—ด์˜ ๊ฐ’ ๋ฒ”์œ„๊ฐ€ ์ž‘์€ ๊ฒฝ์šฐ, O(n + k)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ–๋Š” ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ (k: ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์˜ ๊ฐ€์žฅ ์ž‘์€ ์š”์†Œ๋ถ€ํ„ฐ ๊ฐ€์žฅ ํฐ ์š”์†Œ๊นŒ์ง€์˜ ๋ฒ”์œ„)

  • ์žฅ์ : ์ž…๋ ฅ ๋ฐ์ดํ„ฐ์˜ ๋น„๊ต ์—†์ด ์ด๋ฃจ์–ด์ง€๋Š” ์ •๋ ฌ์ด๋ฏ€๋กœ, ์ •๋ ฌ ์†๋„๊ฐ€ ๋น ๋ฆ„
  • ๋‹จ์ : ํฌ๊ธฐ๊ฐ€ ํ•œ์ •๋˜์–ด ์žˆ๋Š” ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•ด์„œ๋งŒ ์ •๋ ฌํ•  ์ˆ˜ ์žˆ์Œ
  • ์ •๋ ฌ์˜ ๋ชฉ์ ์€ โ€œํƒ์ƒ‰ ๊ธฐ๋Šฅ์˜ ํ–ฅ์ƒโ€์ด๊ณ , ๊ณ„์ˆ˜ ์ •๋ ฌ์€ O(n + k)์˜ ๋งค์šฐ ๋น ๋ฅธ ์†๋„๋ฅผ ๊ฐ€์ง„ ์ •๋ ฌ์ด๋ฏ€๋กœ, ํŠน์ • ์กฐ๊ฑด์— ๋Œ€ํ•ด์„œ๋Š” ๊ฐ€์žฅ ๋น ๋ฅธ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ค‘ ํ•˜๋‚˜์ž„ (๋ณดํ†ต O(n)์œผ๋กœ ๋‚˜์˜ด)

2. ๊ณ„์ˆ˜ ์ •๋ ฌ์˜ ๋™์ž‘ ๊ณผ์ •

  1. ์ž…๋ ฅ ๋ฐฐ์—ด์„ A, ์ตœ์ข… ์ถœ๋ ฅ ๋ฐฐ์—ด์„ B, ์ •๋ ฌ์„ ์œ„ํ•ด ๋งŒ๋“œ๋Š” ๋ฐฐ์—ด์„ C๋ผ๊ณ  ํ•˜์ž.
  2. ๋ฐฐ์—ด-C์˜ ํฌ๊ธฐ๋Š” ๋ฐฐ์—ด-A์˜ ์š”์†Œ ์ค‘ ๊ฐ€์žฅ ํฐ ๊ฐ’์œผ๋กœ ์ง€์ •ํ•œ๋‹ค. (ex) A=[1,5,3,3,2,1] -> C[5])
  3. ๋ฐฐ์—ด-A์˜ ์š”์†Œ๋ณ„ ๊ฐœ์ˆ˜๋ฅผ ๋ฐฐ์—ด-C์˜ ์ธ๋ฑ์Šค๊ฐ’๊ณผ ์ผ์น˜์‹œ์ผœ ์ €์žฅํ•œ๋‹ค. (ex) A=[1,5,3,3,2,1] -> C=[0,2,1,2,0,1])
  4. ๋ฐฐ์—ด-C์—์„œ, 0๋ฒˆ์งธ ๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ์ง์ „ ์š”์†Œ์˜ ๊ฐ’๋“ค๊ณผ ๋”ํ•ด๊ฐ€, ์ƒˆ๋กœ์šด ๋ฐฐ์—ด-C๋ฅผ ๋งŒ๋“ ๋‹ค. (ex) A=[1,5,3,3,2,1] -> C=[0,2,3,5,5,6]
  5. ๋ฐฐ์—ด-B์˜ ํฌ๊ธฐ๋Š” C์˜ ๋งˆ์ง€๋ง‰ ์ธ๋ฑ์Šค์˜ ๊ฐ’์œผ๋กœ ์ง€์ •ํ•œ๋‹ค. (ex) C[5]=6 -> B[6])
  6. ๋ฐฐ์—ด-A์˜ ๋งˆ์ง€๋ง‰ ๋…ธ๋“œ๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ๋ฐฐ์—ด-C์™€ ๋น„๊ตํ•˜์—ฌ B์— ๋Œ€์ž…ํ•œ๋‹ค. (ex) A[6]=1 -> C=[0,2,3,5,5,6]์—์„œ 1์ด ํ•˜๋‚˜ ๋น ์ ธ๋‚˜๊ฐ€๋ฏ€๋กœ C[1]โ€“์ด ๋˜์–ด, C=[0,1,3,5,5,6] -> B=[null,null,1,null,null,null,null]
  7. ๋ฐฐ์—ด-A์˜ ์ฒซ ๋ฒˆ์งธ ๋…ธ๋“œ๊นŒ์ง€ ์™„๋ฃŒํ•  ๋•Œ๊นŒ์ง€ ์œ„ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•œ๋‹ค.

3. ์˜ˆ์ œ์ฝ”๋“œ

์ถœ์ฒ˜: ratsgoโ€™s blog [https://ratsgo.github.io/data%20structure&algorithm/2017/10/16/countingsort/]

# counting_sort (๊ณ„์ˆ˜ ์ •๋ ฌ)

# A: ์ž…๋ ฅ ๋ฐ์ดํ„ฐ
# k : A์˜ ์š”์†Œ ์ค‘ ์ตœ๋Œ“๊ฐ’
def counting_sort(A, k):
    # B: ์ถœ๋ ฅ ๋ฐ์ดํ„ฐ
    # -1๋กœ ์ดˆ๊ธฐํ™”
    B = [-1]*len(A)

    # C: counting ๋ฐ์ดํ„ฐ
    # 0์œผ๋กœ ์ดˆ๊ธฐํ™”
    C = [0] * (k + 1)

    # ๋™์ž‘๊ณผ์ •
    for i in A:
        C[i] += 1

    # C ์ •๋ ฌ
    for i in range(k):
        C[i+1] += C[i]

    # B ์ •๋ ฌ
    for i in reversed(range(len(A))):
        B[C[A[i]] - 1] = A[i]
        C[A[i]] -= 1
    
    return B

input_data = [  1,3,2,4,3,
                2,5,3,1,2,
                3,4,4,3,5,
                1,2,3,5,2,
                3,1,4,3,5,
                1,2,1,1,1  ] 

max_in_input = max(input_data)
print(counting_sort(input_data, max(input_data)))

ํƒœ๊ทธ:

์นดํ…Œ๊ณ ๋ฆฌ:

์—…๋ฐ์ดํŠธ:

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ