ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๋ฐ˜์‘ํ˜•
๋ณ‘ํ•ฉ์ •๋ ฌ๋„ ๋Œ€ํ‘œ์ ์ธ '๋ถ„ํ•  ์ •๋ณต' ๋ฐฉ๋ฒ•์„ ์ฑ„ํƒํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜

ํ€ต ์ •๋ ฌ๊ณผ ๋™์ผํ•˜๊ฒŒ O(N * logN)์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๊ฐ€์ง„๋‹ค. ํ€ต์ •๋ ฌ์€ ํ”ผ๋ฒ—๊ฐ’์— ๋”ฐ๋ผ ์ตœ์•…์˜ ๊ฒฝ์šฐ O(N^2)์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋Š”๋ฐ ๋ณ‘ํ•ฉ์ •๋ ฌ์€ ์ •ํ™•ํžˆ ๋ฐ˜์ ˆ์”ฉ ๋‚˜๋ˆˆ๋‹ค๋Š” ์ ์—์„œ ์ตœ์•…์˜ ๊ฒฝ์šฐ์—๋„ O(N * logN)์„ ๋ณด์žฅํ•œ๋‹ค.

 

 

 

 

์ผ๋‹จ ๋ฐ˜์œผ๋กœ ๋‚˜๋ˆ„๊ณ  ๋‚˜์ค‘์— ํ•ฉ์ณ์„œ ์ •๋ ฌํ•˜์ž

๋ณ‘ํ•ฉ์ •๋ ฌ์€ ํ•ญ์ƒ ๋ฐ˜์œผ๋กœ ๋‚˜๋ˆ„๊ธฐ ๋•Œ๋ฌธ์— ํ”ผ๋ฒ—๊ฐ’์ด ๋”ฐ๋กœ ์—†๋‹ค. ๋ฐ˜์œผ๋กœ ์ชผ๊ฐœ๊ธฐ ๋•Œ๋ฌธ์— ํ•ญ์ƒ logN์„ ๋ณด์žฅํ•œ๋‹ค. ํ•ฉ์น ๋•Œ๋Š” 2์˜ ๋ฐฐ์ˆ˜๋งŒํผ ํ•ฉ์นœ๋‹ค. 

 

 

 

 

# ๋ณ‘ํ•ฉ ์ •๋ ฌ (Merge sort)
# ์ •๋ ฌ๋ฐฐ์—ด์€ ๋ฐ˜๋“œ์‹œ ์ „์—ญ ๋ณ€์ˆ˜๋กœ ์„ ์–ธํ•ด์ค˜์•ผํ•œ๋‹ค. (์ถ”๊ฐ€์ ์ธ ๋ฐฐ์—ด)
sortedArr = []

def merge(arr, start, middle, end): # start : m , end : n
    i = start
    j = middle + 1
    k = start
    
    # ์ž‘์€ ์ˆœ์„œ๋Œ€๋กœ ๋ฐฐ์—ด์— ์‚ฝ์ž…
    # i๋Š” middle๊นŒ์ง€ ๊ฐ€๊ณ  j๋Š” end๊นŒ์ง€ ๊ฐ„๋‹ค.
    while i <= middle and j <= end:
        # ํ•ญ์ƒ i๋ž‘ j๋ฅผ ๋น„๊ตํ•ด์„œ ๋” ์ž‘์€ ๊ฐ’์„ k์— ๋„ฃ๋Š”๋‹ค.
        if arr[i] <= arr[j]:
            sortedArr[k] = arr[i]
            i = i + 1
        else:
            sortedArr[k] = arr[j]
            j = j + 1
        k = k + 1
    
        # ๋‚จ์€ ๋ฐ์ดํ„ฐ๋„ ์‚ฝ์ž…
        if i > middle : # i ๊ฐ€ ๋จผ์ € ๋๋‚œ ๊ฒฝ์šฐ
            for t in range(j, end + 1):
                sortedArr[k] = arr[t]
                k = k + 1
        else: # j๊ฐ€ ๋จผ์ € ๋๋‚œ๊ฒฝ์šฐ
            for t in range(i, middle + 1):
                sortedArr[k] = arr[t]
                k = k + 1
        
        
        # ์ •๋ ฌ๋œ ๋ฐฐ์—ด์„ ์‚ฝ์ž…
        for t in range(start, end+1):
            arr[t] = sortedArr[t]
            

def merge_sort(arr, start, end):
    # ํฌ๊ธฐ๊ฐ€ 1๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ
    if start < end :
        middle = (start + end) / 2
        merge_sort(arr, start, middle)
        merge_sort(arr, middle + 1, end)
        merge(arr, start, middle, end)
    
    return arr
        
        

test = [7,6,5,8,3,5,9,1]

print("์ •๋ ฌ๋œ ๋ฐฐ์—ด : {}".format(merge_sort(test, 0, len(test)-1)))

์ด ์ฝ”๋“œ ์‹คํ–‰์•ˆ๋จ;

 

๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€