YS's develop story

๋ณ‘ํ•ฉ ์ •๋ ฌ (Merge Sort) ์ •๋ฆฌ ๋ณธ๋ฌธ

Algorithm

๋ณ‘ํ•ฉ ์ •๋ ฌ (Merge Sort) ์ •๋ฆฌ

Yusang 2021. 7. 31. 09:17

๐Ÿ‘ฉ‍๐Ÿ’ป ๋ณ‘ํ•ฉ ์ •๋ ฌ (Merge Sort) ์ •๋ฆฌ with Python

๐Ÿณ ๋ณ‘ํ•ฉ ์ •๋ ฌ (Merge Sort)์ด๋ž€?

  1. ์žฌ๊ท€ ์šฉ๋ฒ•์„ ํ™œ์šฉํ•œ ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ž…๋‹ˆ๋‹ค.
  2. ๋ฆฌ์ŠคํŠธ๋ฅผ ์ ˆ๋ฐ˜์œผ๋กœ ์ž˜๋ผ ๋น„์Šทํ•œ ํฌ๊ธฐ์˜ ๋‘ ๋ฆฌ์ŠคํŠธ๋กœ ๋‚˜๋ˆ•๋‹ˆ๋‹ค.
  3. ๊ฐ ๋ถ€๋ถ„ ๋ฆฌ์ŠคํŠธ๋ฅผ ์žฌ๊ท€์ ์œผ๋กœ ๋ณ‘ํ•ฉ ์ •๋ ฌ์„ ์ด์šฉํ•ด ์ •๋ ฌํ•ฉ๋‹ˆ๋‹ค.
  4. ๋‘ ๋ถ€๋ถ„ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋‹ค์‹œ ํ•˜๋‚˜์˜ ์ •๋ ฌ๋œ ๋ฆฌ์ŠคํŠธ๋กœ ๋ณ‘ํ•ฉํ•ฉ๋‹ˆ๋‹ค.

 Merge Sort๋Š” Divide And Conquer์˜ ๋Œ€ํ‘œ์ ์ธ ์˜ˆ์‹œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ž…๋‹ˆ๋‹ค.

 

๐Ÿฅ˜ ๋ณ‘ํ•ฉ ์ •๋ ฌ ๊ตฌํ˜„ with Python

def mergeSort(data):
    if len(data) <= 1:
        return data
    medium = len(data) // 2
    left = mergeSort(data[:medium])
    right = mergeSort(data[medium:])
    return merge(left, right)


def merge(left, right):
    merged = list()
    leftPoint, rightPoint = 0, 0

    while len(left) > leftPoint and len(right) > rightPoint:
        if left[leftPoint] > right[rightPoint]:
            merged.append(right[rightPoint])
            rightPoint += 1
        else:
            merged.append(left[leftPoint])
            leftPoint += 1
    while len(left) > leftPoint:
        merged.append(left[leftPoint])
        leftPoint += 1

    while len(right) > rightPoint:
        merged.append(right[rightPoint])
        rightPoint += 1

    return merged

 

 

๐Ÿช ์‹œ๊ฐ„ ๋ณต์žก๋„ ๋ถ„์„

O(n) * O(log n) = O(n log n)

Comments