基于python的冒泡排序和选择排序

0.产生7000长度的乱序列表

```import random

a_list = list(range(1,7000 + 1))
normal_list = random.sample(a_list, k=len(a_list))
normal_list[:5]```

[2780, 397, 5063, 6494, 1245]

0.1 保存此乱序列表

```import pickle

with open('normal_list.pickle', 'wb') as file:
pickle.dump(normal_list, file)```

0.2 加载此乱序列表

```import pickle

with open('normal_list.pickle', 'rb') as file:

0.3 计时装饰器

```from time import time

def timer(func):
def inner(*args,**kwargs):
start = time()
result = func(*args,**kwargs)
end = time()
usedTime = 1000 * (end - start)
print("%s function used %.2f ms" %(func.__name__,usedTime))
return result
return inner```

1.冒泡排序

```@timer
def bubble_sort(normal_list):
length = len(normal_list)
for i in range(length, 1, -1):
for j in range(0, i-1):
if normal_list[j] > normal_list[j+1]:
normal_list[j], normal_list[j+1] = normal_list[j+1], normal_list[j]

with open('normal_list.pickle', 'rb') as file:
bubble_sort(normal_list)
print(normal_list[:10])
print(normal_list[-10:])```

bubble_sort function used 7858.98 ms [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [6991, 6992, 6993, 6994, 6995, 6996, 6997, 6998, 6999, 7000]

2.选择排序

```@timer
def select_sort(normal_list):
length = len(normal_list)
new_list = []
for i in range(length, 1, -1):
max_index = 0
max_value = normal_list[0]
for j in range(1, i):
if normal_list[j] > max_value:
max_value = normal_list[j]
max_index = j
normal_list[i-1], normal_list[max_index] = normal_list[max_index], normal_list[i-1]

with open('normal_list.pickle', 'rb') as file:
select_sort(normal_list)
print(normal_list[:10])
print(normal_list[-10:])```

select_sort function used 2018.90 ms [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [6991, 6992, 6993, 6994, 6995, 6996, 6997, 6998, 6999, 7000]

0 条评论

相关文章

33250

13310

40830

你所能用到的无损压缩编码(二）

上个月项目荷兰大佬要检查，搞的我想写的东西不断推迟，现在检查完了，我决定继续把我想写的这整个一个系列写完，上一次写的是最简单的无损编码行程编码，这一次...

37590

17630

3.9K110

Java 8：HashMap的性能提升

HashMap是一个高效通用的数据结构，它在每一个Java程序中都随处可见。先来介绍些基础知识。你可能也知道，HashMap使用key的hashCode()和e...

8720

90380

363110