查看: 2005|回复: 0
收起左侧

[资料分享] 【排序】计数排序法python实现

Lihoon 2020-3-17 20:13:42 | 显示全部楼层 |阅读模式
邀请回答

马上注册,享受更多特权

您需要 登录 才可以下载或查看,没有帐号?立即注册   

x
本帖最后由 Lihoon 于 2020-3-17 20:15 编辑

建立随机数组生成程序:random_list.py
  1. #-*- coding:utf-8 -*-
  2. # Created Date: 2020/03/10

  3. import random

  4. def random_list(n):
  5.         """返回一个长度为n的随机数列表,数值为[0,1000)"""
  6.         print("Input number is :{}".format(n))
  7.         iList = []
  8.         for num in range(n):
  9.                 iList.append(random.randrange(1000))
  10.         return iList
  11.         
  12. if __name__ == "__main__":
  13.         iList = random_list(10)
  14.         print(iList)
复制代码
建立计数排序算法程序:counting_sort.py
  1. #-*- coding:utf-8 -*-
  2. #Created Date: 2020/03/17

  3. from random_list import random_list
  4. from sys import argv

  5. # input_num = argv[1]        
  6. # 不使用外部输入,在程序运行后调用input()输入数组长度
  7. list = random_list(int(input("Please input the list length\n>>>")))

  8. def counting_sort(list):
  9.         """定义计数排序算法函数"""
  10.         if len(list) <= 1:
  11.                 return iList
  12.         
  13.         # 获得输入数组的长度,然后定义一个长度一样的空数组
  14.         len_list = len(list)
  15.         new_list = [None]*len_list
  16.         
  17.         # 依次取出数字,统计比当前数字小的次数和相等的次数
  18.         # 然后将与基数相等的数字放到比基数小的数字的次数位置
  19.         for idx_a in range(len_list):
  20.                 small = 0
  21.                 same = 0
  22.                 for idx_b in range(len_list):
  23.                         if list[idx_b] < list[idx_a]:
  24.                                 small += 1
  25.                         
  26.                         elif list[idx_b] == list[idx_a]:
  27.                                 same += 1
  28.                 for idx_c in range(small, small + same):
  29.                         new_list[idx_c] = list[idx_a]
  30.         return new_list
  31.         
  32. if __name__ == "__main__":
  33.         print("source list: {}".format(list))
  34.         print("new list: {}".format(counting_sort(list)))
  35.         
复制代码
命令行输入指令:
  1. python counting_sort.py
复制代码
在弹出的提示框中输入:10 并按回车
  1. Please input the list length
  2. >>>10
复制代码
得到的计算结果为:
  1. Input number is :10
  2. source list: [271, 349, 368, 100, 649, 983, 238, 164, 508, 311]
  3. new list: [100, 164, 238, 271, 311, 349, 368, 508, 649, 983]
复制代码

评分

参与人数 1水滴 +1 贡献 +1 收起 理由
火浴 + 1 + 1 赞一个!

查看全部评分





上一篇:【排序】归并排序法python实现
下一篇:查找数字python实现

已有 0 人打赏作者

1 喜欢他/她就送朵鲜花吧,赠人玫瑰,手有余香! 鲜花榜单
  • +1

    hold住,要hold住,必须的!

回复 邀请回答送花

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册   

本版积分规则

有技术问题,就上汇川技术社区

INOVANCE汇川技术 公众号

扫码下载掌上汇川APP

全国服务热线:8:30-17:30

4000-300124

苏州地址:江苏省苏州市吴中区越溪友翔路16号

深圳地址:深圳市龙华新区观澜街道高新技术产业园汇川技术总部大厦

Copyright © 2003-2100 汇川技术 Powered by Discuz! X3.4 ( 苏ICP备12002088号 )
快速回复 返回列表 返回顶部