美文网首页
计数排序

计数排序

作者: 养乐多__ | 来源:发表于2019-01-08 23:11 被阅读0次
  • 计数排序伪代码:
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] 对应的计数为1
    else
        hash[number] <- hash[number] + 1      // 若此数已存在,计数加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)   // 用函数findMax找出数组a的最大值67,赋值给max
newArr <- {}       // 声明一个新的数组
while index2 <= max   // 或写为 index2<max+1,index2可从0取到max
    count <- hash[index2]       // 此数值的个数
    if count != undefined         // 如果 count 存在
        countIndex <- 0
        while countIndex < count     // count 等于几就把这个数 push 几次
            newArr.push(index2)
            countIndex <- countIndex + 1
        end
    end
    index2 <- index2 + 1
end
print newArr
  • 计数排序流程图:
计数排序流程图

相关文章

网友评论

      本文标题:计数排序

      本文链接:https://www.haomeiwen.com/subject/ixpirqtx.html