counting
,메모리 공간
, 수의 범위
계수 정렬은 주어진 배열에서 특정 숫자가 몇 번 등장했는지 counting하여 정렬을 수행하는 기법입니다. 숫자간 비교 없이 단순히 배열을 순회하고, 이후에 개수가 기록된 테이블을 순회하기 때문에, 시간복잡도는 O(n+k)입니다. 여기서 n은 배열의 원소의 개수, k는 숫자의 범위입니다.
시간복잡도에서 알 수 있는 계수 정렬의 장점은, k가 작을 때, 즉 수의 범위가 배열의 원소의 수보다 작을 때 효율적이라는 것입니다. 반면 배열의 원소 수보다 숫자의 범위가 훨씬 커지게 되면 메모리 공간을 낭비하게 되고 시간도 더 오래걸리게 됩니다.
# Counting sort in Python programming
def countingSort(array):
size = len(array)
output = [0] * size
# Initialize count array
count = [0] * 10
# Store the count of each elements in count array
for i in range(0, size):
count[array[i]] += 1
# Store the cummulative count
for i in range(1, 10):
count[i] += count[i - 1]
# Find the index of each element of the original array in count array
# place the elements in output array
i = size - 1
while i >= 0:
output[count[array[i]] - 1] = array[i]
count[array[i]] -= 1
i -= 1
# Copy the sorted elements into original array
for i in range(0, size):
array[i] = output[i]
data = [4, 2, 2, 8, 3, 3, 1]
countingSort(data)
print("Sorted Array in Ascending Order: ")
print(data)