阿摩線上測驗 登入

申論題資訊

試卷:104年 - 104 一般警察特種考試_二等_刑事警察人員犯罪分析組:計算機概論(包括計算機結構、資料結構、程式設計)#22638
科目:計算機概論、大意(資訊科學概論,電腦常識,電子計算機概論)
年份:104年
排序:0

題組內容

四、下列 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)