|
邀请回答
马上注册,享受更多特权
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
本帖最后由 Lihoon 于 2020-3-17 20:15 编辑
建立随机数组生成程序:random_list.py- #-*- coding:utf-8 -*-
- # Created Date: 2020/03/10
- import random
- def random_list(n):
- """返回一个长度为n的随机数列表,数值为[0,1000)"""
- print("Input number is :{}".format(n))
- iList = []
- for num in range(n):
- iList.append(random.randrange(1000))
- return iList
-
- if __name__ == "__main__":
- iList = random_list(10)
- print(iList)
复制代码 建立计数排序算法程序:counting_sort.py
- #-*- coding:utf-8 -*-
- #Created Date: 2020/03/17
- from random_list import random_list
- from sys import argv
- # input_num = argv[1]
- # 不使用外部输入,在程序运行后调用input()输入数组长度
- list = random_list(int(input("Please input the list length\n>>>")))
- def counting_sort(list):
- """定义计数排序算法函数"""
- if len(list) <= 1:
- return iList
-
- # 获得输入数组的长度,然后定义一个长度一样的空数组
- len_list = len(list)
- new_list = [None]*len_list
-
- # 依次取出数字,统计比当前数字小的次数和相等的次数
- # 然后将与基数相等的数字放到比基数小的数字的次数位置
- for idx_a in range(len_list):
- small = 0
- same = 0
- for idx_b in range(len_list):
- if list[idx_b] < list[idx_a]:
- small += 1
-
- elif list[idx_b] == list[idx_a]:
- same += 1
- for idx_c in range(small, small + same):
- new_list[idx_c] = list[idx_a]
- return new_list
-
- if __name__ == "__main__":
- print("source list: {}".format(list))
- print("new list: {}".format(counting_sort(list)))
-
复制代码 命令行输入指令:
在弹出的提示框中输入:10 并按回车
- Please input the list length
- >>>10
复制代码 得到的计算结果为:
- Input number is :10
- source list: [271, 349, 368, 100, 649, 983, 238, 164, 508, 311]
- new list: [100, 164, 238, 271, 311, 349, 368, 508, 649, 983]
复制代码
|
评分
-
查看全部评分
上一篇: 【排序】归并排序法python实现下一篇: 查找数字python实现
1
喜欢他/她就送朵鲜花吧,赠人玫瑰,手有余香!
鲜花榜单
-
+1
hold住,要hold住,必须的!
|