ID_DI
DI's study notes
ID_DI
전체 방문자
오늘
어제
  • 분류 전체보기 (85)
    • Deep-Learning (3)
      • CNN (2)
      • NLP (1)
    • Data_Python (6)
      • Numpy (0)
      • Matplotlib (4)
    • Python (8)
      • Python Algorithm (6)
    • Java (36)
      • Java(base) (33)
      • Java practice(base) (2)
    • Git (12)
    • Algorithm (7)
    • etc (7)
    • linux (1)
    • DeskSetup (0)
    • TIL_모각코 (4)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 커밋
  • Github
  • 알고리즘
  • staged
  • git add.
  • 자바
  • matplotlib
  • string to int
  • git
  • java
  • java base
  • java 기초
  • binarySearch
  • java.net
  • java.lang
  • 합병정렬
  • 파이썬
  • Python
  • 정렬
  • README.md

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ID_DI

DI's study notes

[python](알고리즘) mergeSort 병합정렬(합병정렬) 구현
Python/Python Algorithm

[python](알고리즘) mergeSort 병합정렬(합병정렬) 구현

2021. 10. 1. 23:33

Merge sort(합병정렬) 구현

코드

def merge_sort(list):
    if len(list) <= 1:  # base case: 리스트에 원소가 하나 밖에 없을 때
        return list

    mid = len(list) // 2  # 리스트의 중간지점
    left_list = list[:mid]  # 리스트의 왼쪽 부분
    right_list = list[mid:]  # 리스트의 오른쪽 부분

    left_list = merge_sort(left_list)  # 재귀함수를 호출하여 다시 나눈다.
    right_list = merge_sort(right_list)

    return merge(left_list, right_list)  # 왼쪽부터 오른쪽으로 merge

def merge(left, right):
    i = 0
    j = 0
    merge_list = []

    while i < len(left) and j < len(right):  # left, right 가 아직 남아있을 때
        if right[j] < left[i]:
            merge_list.append(right[j])
            j += 1
        else:
            merge_list.append(left[i])
            i += 1

    if (i < len(left)): #left 만 남아있을 때, 리스트에 리스트를 합친다.
        merge_list += left[i:len(left)]
    else:
        merge_list += right[j:len(right)]

    return merge_list
data_list = [-1, 10, 20, 7, 15, 30, 40, 50, 32, 5]
print(merge_sort(data_list))

실행결과

[-1, 5, 7, 10, 15, 20, 30, 32, 40, 50]

시간복잡도

O(nlogn)

'Python > Python Algorithm' 카테고리의 다른 글

[python](알고리즘) quickSort 퀵정렬(랜덤 피봇) 구현  (0) 2021.10.06
[python] factorial 함수, 재귀함수 구현  (0) 2021.08.27
[python] (알고리즘) binarySearch (이진탐색) 구현  (0) 2021.08.27
[python](자료구조) Queue class 구현  (0) 2021.08.25
[python](자료구조) stack class 구현  (0) 2021.08.25
    'Python/Python Algorithm' 카테고리의 다른 글
    • [python](알고리즘) quickSort 퀵정렬(랜덤 피봇) 구현
    • [python] factorial 함수, 재귀함수 구현
    • [python] (알고리즘) binarySearch (이진탐색) 구현
    • [python](자료구조) Queue class 구현
    ID_DI
    ID_DI
    Computer Vision

    티스토리툴바