day28
求排序
10个数,按从小到大排序
分析
1.直接双循环实现,冒泡和选择排序
2.直接排序方法或函数 list.sort()或sorted()
编码实现
1.编码实现(选择和冒泡排序)
import random
lst=[x for x in range(1,11)]
random.shuffle(lst)
n=len(lst)
print(lst)
for i in range(n-1):
for j in range(i+1,n): #先排lst[0],然后继续
if lst[i]>lst[j]:
temp=lst[i]
lst[i]=lst[j]
lst[j]=temp
print(lst)
运行结果
[6, 4, 10, 9, 5, 3, 7, 8, 1, 2]
[1, 6, 10, 9, 5, 4, 7, 8, 3, 2]
[1, 2, 10, 9, 6, 5, 7, 8, 4, 3]
[1, 2, 3, 10, 9, 6, 7, 8, 5, 4]
[1, 2, 3, 4, 10, 9, 7, 8, 6, 5]
[1, 2, 3, 4, 5, 10, 9, 8, 7, 6]
[1, 2, 3, 4, 5, 6, 10, 9, 8, 7]
[1, 2, 3, 4, 5, 6, 7, 10, 9, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 10, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
import random
lst=[x for x in range(1,11)]
random.shuffle(lst)
n=len(lst)
print(lst)
for i in range(n-1,0,-1):
for j in range(n-1,0,-1):#两两比较,逆泡冒先排lst[0],然后继续
if lst[j]<lst[j-1]:
temp=lst[j]
lst[j]=lst[j-1]
lst[j-1]=temp
print(lst)
运行结果
[3, 5, 9, 1, 8, 10, 4, 2, 7, 6]
[1, 3, 5, 9, 2, 8, 10, 4, 6, 7]
[1, 2, 3, 5, 9, 4, 8, 10, 6, 7]
[1, 2, 3, 4, 5, 9, 6, 8, 10, 7]
[1, 2, 3, 4, 5, 6, 9, 7, 8, 10]
[1, 2, 3, 4, 5, 6, 7, 9, 8, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2.编码实现(直接方法或函数)
import random
lst=[x for x in range(1,11)]
random.shuffle(lst)
print(lst)
lst.sort()
print(lst)
运行结果
[5, 9, 2, 8, 7, 4, 1, 3, 10, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
import random
lst=[x for x in range(1,11)]
random.shuffle(lst)
print(lst)
lst1=sorted(lst)
print(lst1)
运行结果
[7, 6, 4, 9, 1, 10, 2, 8, 5, 3]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]