虽然说Python里面提供了现成的排序方式,而且效率也非常高,但是该会的还是得会。这里我也就不多说什么了,代码+注释,自己看吧!
在这里为了B站视频测试二者效率,所以增加了随机数和时间的计算。
from time import time
from random import randint
# 全局变量,便于修改
gl_length = 100
# 定义空列表,存放排序数据
num_list = []
# 产生随机数函数
def listRandom(num_list):
i = 0
while i < gl_length:
# 随机范围0~999
num_list.append(randint(0, 1000))
i += 1
# 遍历函数
def listForeach(num_list):
print("=" * 80)
# 为了换行的美观,没有直接使用 for i in num_list
for i in range(gl_length):
print(num_list[i], end="\t")
if ((i + 1) % 10) == 0:
print("\n")
# 冒泡排序
def bubbleSort(num_list):
star_time = time()
for x in range(gl_length - 1):
for y in range(gl_length - 1 - x):
if num_list[y] >= num_list[y + 1]:
num_list[y], num_list[y + 1] = num_list[y + 1], num_list[y]
end_time = time()
return end_time - star_time
def partition(num_list, low, high):
i = (low - 1)
pivot = num_list[high]
for j in range(low, high):
# 当前元素小于或等于 pivot
if num_list[j] <= pivot:
i = i + 1
num_list[i], num_list[j] = num_list[j], num_list[i]
num_list[i + 1], num_list[high] = num_list[high], num_list[i + 1]
return (i + 1)
# 快速排序函数
def quickSort(num_list, low, high):
star_time = time()
if low < high:
pi = partition(num_list, low, high)
quickSort(num_list, low, pi - 1)
quickSort(num_list, pi + 1, high)
end_time = time()
return end_time - star_time
listRandom(num_list)
listForeach(num_list)
use_time = quickSort(num_list, 0, gl_length - 1)
# use_time = bubbleSort(num_list)
listForeach(num_list)
print("USE TIME:"+ str(use_time))
来源:CSDN
作者:JP.Shame
链接:https://blog.csdn.net/qq_25404477/article/details/103480089