題組內容

四、下列 C 語言函數是氣泡排序演算法 

(二)若 iArray 陣列的內容都在 0~9 的範圍內,共有 n 筆,請寫出計數排序(counting sort)演算法。(15 分)

詳解 (共 1 筆)

詳解 提供者:hchungw

def counting_sort(iArray):
    # Since the range is 0-9, the size of the count array will be 10.
    count = [0] * 10
    output = [0] * len(iArray)

    # Count each number in the array.
    for num in iArray:
        count[num] += 1

    # Accumulate the count.
    for i in range(1, 10):
        count[i] += count[i - 1]

    # Place the elements in their correct position and build the output array.
    for num in reversed(iArray):
        output[count[num] - 1] = num
        count[num] -= 1

    return output

# To sort an array, you would call the function like this:
# sorted_array = counting_sort(iArray)