- 計數(shù)排序偽代碼:
a <- {
'0':0, '1':2, '2':1, '3':56, '4':3, '5':67, '6':3, 'length:7'
}
hash <- {} // 定義一個空的 hash
// 入桶
index <- 0
while index < a['length'] // index可取到的值0、1、2、3、4、5、6
number <- a[index] // number可取到的值0、2、1、56、3、67
if hash[number] == undefined // hash[number] 不存在時
hash[number] = 1 // hash[number] 對應(yīng)的計數(shù)為1
else
hash[number] <- hash[number] + 1 // 若此數(shù)已存在,計數(shù)加1
end
index <- index + 1
end // hash={‘0’:1,‘1’:1,‘2’:1,‘3’:2,‘56’:1,‘67’:1}
// 出桶,遍歷 hash
index2 <- 0
max <- findMax(a) // 用函數(shù)findMax找出數(shù)組a的最大值67,賦值給max
newArr <- {} // 聲明一個新的數(shù)組
while index2 <= max // 或?qū)憺?index2<max+1,index2可從0取到max
count <- hash[index2] // 此數(shù)值的個數(shù)
if count != undefined // 如果 count 存在
countIndex <- 0
while countIndex < count // count 等于幾就把這個數(shù) push 幾次
newArr.push(index2)
countIndex <- countIndex + 1
end
end
index2 <- index2 + 1
end
print newArr
- 計數(shù)排序流程圖:
計數(shù)排序流程圖