[기술면접/알고리즘] Radix Sort

강민혁·2023년 2월 7일
0

Radix Sort에 대해 설명하세요

Keyword

자리수, 메모리, 비교 연산


Script

기수 정렬은 낮은 자리수부터 비교하며 정렬을 수행하는 알고리즘입니다. 비교 연산을 수행하지 않기 때문에 정렬 속도가 빠르지만, 추가적인 메모리 공간을 필요로 합니다. 또 부동 소수점과 같이 자릿수가 없는 것은 정렬할 수 없습니다.

동작원리를 간단히 설명드리자면, 가장 작은 자리수부터 비교하는 LSD(Least-Significant-Digit)의 경우, 일의 자리를 기준으로 배열을 하나하나 살펴보며, 해당하는 자릿수 버킷 큐에 해당 값을 넣어줍니다. 그리고 큐에 있는 모든 원소를 꺼내어 일의 자리로 정렬된 결과를 도출합니다. 마찬가지로 이 과정을 최대 자리수까지 반복하면 정렬이 수행됩니다.

정렬할 숫자의 자릿수를 d라고 할때 시간복잡도는 항상 O(dn)입니다.


Additional

그림

코드 (python)

# Using counting sort to sort the elements in the basis of significant places
def countingSort(array, place):
    size = len(array)
    output = [0] * size
    count = [0] * 10

    # Calculate count of elements
    for i in range(0, size):
        index = array[i] // place
        count[index % 10] += 1

    # Calculate cumulative count
    for i in range(1, 10):
        count[i] += count[i - 1]

    # Place the elements in sorted order
    i = size - 1
    while i >= 0:
        index = array[i] // place
        output[count[index % 10] - 1] = array[i]
        count[index % 10] -= 1
        i -= 1

    for i in range(0, size):
        array[i] = output[i]


# Main function to implement radix sort
def radixSort(array):
    # Get maximum element
    max_element = max(array)

    # Apply counting sort to sort elements based on place value.
    place = 1
    while max_element // place > 0:
        countingSort(array, place)
        place *= 10


data = [121, 432, 564, 23, 1, 45, 788]
radixSort(data)
print(data)
profile
with programming

0개의 댓글