本博文示例为自己指定一定范围,生成指定个数的随机数,再对生成的随机数进行排序,并记录排序所花时间。
生成指定范围、指定个数随机数代码:
import random
def generate_point_range(gene_size, min_val, max_val):
num_list = []
i = 0
while i < gene_size:
num_list.append(random.randint(min_val, max_val))
i += 1
return num_list
插入排序代码:
import randomgenerate
import time
def insert_sort(num):
start_time = time.time()
num_len = len(num)
for i in range(1, num_len):
key = num[i]
j = i - 1
while j >= 0:
if num[j] > key:
num[j+1], num[j] = num[j], key
j -= 1
print 'insert sort used:', time.time() - start_time, 's'
return num
def main():
num = randomgenerate.generate_point_range(100, 0, 1000)
print 'before sort:', num
insert_sort(num)
print 'after sort', num
if __name__ == "__main__":
main()