ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 정렬 알고리즘(Sort Algorithm) 모음(Python, 파이썬)
    카테고리 없음 2019. 1. 21. 13:09

    삽입 정렬(Insertion Sort)

    1

    2

    3

    4

    5

    6

    7

    8

    9

    def insertionSort(x):

    for size in range(1,len(x)):

    val = x[size]

    i = size

    while i > 0 and x[i-1] > val:

    x[i] = x[i-1]

    i-= 1

    x[i] = val

    return x

    버블 정렬(Bubble Sort)

    1

    2

    3

    4

    5

    6

    def bubbleSort(x):

    for size in reversed(range(len(x))):

    for i in range(size):

    if x[i] > x[i+1]:

    x[i], x[i+1] = x[i+1], x[i]

    return x

    선택 정렬(Selection Sort)

    1

    2

    3

    4

    5

    6

    7

    8

    9

    def selection_sort(x):

    n = len(x)

    for i in range(0, n-1):

    min_idx = i

    for j in range(i+1,n):

    if x[j] < x[min_idx]:

    min_idx = j

    x[i], x[min_idx] = x[min_idx], x[i]

    return x

    쉘 정렬(shell Sort)

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    def gapInsertionSort(x, start, gap):

    for target in range(start+gap, len(x), gap):

    val = x[target]

    i = target

    while i > start:

    if x[i-gap]> val:

    x[i] = x[i-gap]

    else:

    break

    i -= gap

    x[i] = val

    def shellSort(x):

    gap = len(x) // 2

    while gap > 0:

    for start in range(gap):

    gapInsertionSort(x, start, gap)

    gap = gap // 2

    return x

    병합 정렬(Merge Sort)

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    def merge_sort(list):

    if len(list) <= 1:

    return list

    mid = len(list) // 2

    leftList = list[:mid]

    rightList = list[mid:]

    leftList = merge_sort(leftList)

    rightList = merge_sort(rightList)

    return merge(leftList, rightList)

    def merge(left, right):

    result = []

    while len(left) > 0 or len(right) > 0:

    if len(left) > 0 and len(right) > 0:

    if left[0] <= right[0]:

    result.append(left[0])

    left = left[1:]

    else:

    result.append(right[0])

    right = right[1:]

    elif len(left) > 0:

    result.append(left[0])

    left = left[1:]

    elif len(right) > 0:

    result.append(right[0])

    right = right[1:]

    return result

    퀵 정렬(Quick Sort)

    1

    2

    3

    4

    5

    6

    7

    8

    9

    def quick_sort(array):

    array_length = len(array)

    if array_length <= 1:

    return array

    else:

    pivot = array[0]

    greater = [ element for element in array[1:] if element > pivot]

    lesser = [ element for element in array[1:] if element <= pivot]

    return quick_sort(lesser) + [pivot] + quick_sort(greater)


Designed by Tistory.