已知一个列表,自己写算法实现列表的排序
思路:假设第一个值是最大的,然后拿这个值和其他值一次比较交换,实现最大值放在最前面,然后假设第二值是最大的重复进行比较:
第一次代码:
#降序排序
numbers= [1,2,5,0,9,6,3,8,4,7]
i = 1
n = 1
while n < len(numbers):
m=n
i=n
number_max=numbers[n-1]
while i < len(numbers):
if number_max < numbers[i]:
middle_num = numbers[i]
numbers[i] = number_max
numbers[n-1] = middle_num
number_max = numbers[n-1]
i+=1
n+=1
print(numbers)
第二次代码优化:
numbers= [1,2,5,0,9,6,3,8,4,7]
i = 1
n = 1
while n < len(numbers):
m=n
i=n
number_max=numbers[n-1]
while i < len(numbers):
if number_max < numbers[i]:
numbers[n-1],numbers[i] = numbers[i],numbers[n-1] #实现快速互换
number_max = numbers[n-1]
i+=1
n+=1
print(numbers)
第三次代码优化:while一般都是针对一个固定的条件,这里应该使用for循环
numbers= [1,2,5,0,9,6,3,8,4,7]
l = len(numbers)
for i in range(0,l):
for n in range(i+1, l):
if numbers[i] < numbers[n]:
numbers[i], numbers[n] = numbers[n], numbers[i]
print(numbers)
测试俩种代码实现的性能差异:
import time
import random
import numpy as np
def yezi(listNumbers):
starttime= time.time()
numbers = listNumbers
i = 1
n = 1
while n < len(numbers):
m=n
i=n
number_max=numbers[n-1]
while i < len(numbers):
if number_max < numbers[i]:
middle_num = numbers[i]
numbers[i] = number_max
numbers[n-1] = middle_num
number_max = numbers[n-1]
i+=1
n+=1
endtime= time.time()
print('yei time')
print(endtime-starttime)
def Lijn(listNumbers):
starttime= time.time()
numbers = listNumbers
l = len(numbers)
for i in range(0,l):
for n in range(i+1, l):
if numbers[i] < numbers[n]:
numbers[i], numbers[n] = numbers[n], numbers[i]
endtime= time.time()
print('Lijn time')
print(endtime-starttime)
if __name__ == "__main__":
#随机生成数组 最小 最大 多少个
random_list=np.random.randint(0,15000,8000)
print(random_list)
yezi(random_list)
Lijn(random_list)
冒泡排序法:
#冒泡排序
numbers= [1,2,5,0,9,6,3,8,4,7]
for i in range(l-1):
for j in range(0, l-1-i):
if numbers[j] < numbers[j+1]:
numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
print(numbers)
从性能上来说,选择排序比冒泡排序要优一些。