排序算法——计数排序

 a <- {
        '0':0,
        '1':2,
        '2':1,
        '3':56,
        '4':3,
        '5':67,
        '6':4,
        'length':7
    }
    
hash <- {
    //  0 2 1 56 3 67 3 引入后面的计数排序2
}

index <- 0

while (index < a['length'])
    number = a[index]  //0,2,1,56,3,67,4
    if hash[number] == undefined  //hash[number] 不存在
        hash[number] = 1
    else   //hash[number]存在
        hash[number] = hash[number] + 1
    end
    index <- index + 1
end

index2 <- 0

max <- findMax(a)

newArr <- {}

while (index2 < max + 1) //index2 == max(67) 是可以出现的,index2<68
    count = hash[index2]
    if count != undefined
        countIndex = 0
        while (countIndex < count)
            newArr.push(index2)
            countIndex <- countIndex + 1
        end
    end
        index2 <- index2 + 1
end
print newArr
end

实例:
0,2,1,56,3,67,3
hash = {}
index == 0
number = 0
hash = {‘0’: 1}

index == 1
number = 2
hash = {‘0’:1, ‘2’:1}

index == 2
number = 1
hash = {‘0’:1, ‘1’:1 , ‘2’:1}

index == 3
number = 56
hash = {‘0’:1, ‘1’:1 , ‘2’:1, ‘56’:1}

index == 4
number = 3
hash = {‘0’:1, ‘1’:1 , ‘2’:1, ‘3’:1 , ‘56’:1}

index == 5
number = 67
hash = {‘0’:1, ‘1’:1 , ‘2’:1, ‘3’:1 , ‘56’:1, ‘67’:1}

index == 6
number = 3
hash = {
‘0’:1,
‘1’:1 ,
‘2’:1,
‘3’:2 ,
‘56’:1,
‘67’:1
}

入桶

出桶
index2 = 0
newArr = [0];
index2 = 1
newArr = [0,1];
index2 = 2
newArr = [0, 1, 2];
index2 = 3
newArr = [0, 1, 2, 3, 3];
index2 = 4
什么都不做
index2 = 5
什么都不做


index2 = 56
newArr =[0, 1, 2, 3, 3, 56]

index2 = 67
newArr =[0, 1, 2, 3, 3, 56, 67]

///

if count == 1
    newArr.push(index2)
elseif count == 2
	newArr.push(index2)
	newArr.push(index2)
else count == 3
	newArr.push(index2)
	newArr.push(index2)
	newArr.push(index2)
end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值