-
Notifications
You must be signed in to change notification settings - Fork 0
/
排序问题
70 lines (65 loc) · 1.66 KB
/
排序问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
list_a.sort() #改变list_a为有序状态
list_b = sorted( list_a ) #将list_a存为有序的list_b
#几种排序算法的实现
#选择排序法,每次遍历挑出最小值,O(n*n)
l_num=[1,34,4,63,4,7,47,2,48,654,4,57,32]
for i in range(len(l_num)-1):
imin=i
for j in range(i+1,len(l_num)):
if l_num[j]<l_num[imin]:
imin=j
temp=l_num[i]
l_num[i]=l_num[imin]
l_num[imin]=temp
print(l_num)
#冒泡法,每次和相邻比较,O(n*n)
l_num=[1,34,4,63,4,7,47,2,48,654,4,57,32]
for i in range(len(l_num)):
for j in range(len(l_num)-i-1):
if l_num[j]>l_num[j+1]:
temp=l_num[j]
l_num[j]=l_num[j+1]
l_num[j+1]=temp
print(l_num)
#插入排序,像打扑克的时候,每次输入都将它放在合适位置,O(n*n)
def Insertsort(b,a):
if a==[]:
a.append(b)
return a
for item in a:
if item>b:
i=a.index(item)
c=a[i:]
d=a[:i]
d.append(b)
a=d+c
return a
a.append(b)
return a
l_num=[1,34,4,63,4,7,47,2,48,654,4,57,32]
ans=[]
for item in l_num:
ans=Insertsort(item,ans)
print(ans)
#二分插入排序
def Insertsort2(b,a):
left=0
right=len(a)-1
while(left<=right):
mid=(left+right)//2
if a[mid]>b:
right=mid-1
else:
left=mid+1
a_l=a[:left]
a_r=a[left:]
a_l.append(b)
return a_l+a_r
l_num=[1,34,4,63,4,7,47,2,48,654,4,57,32]
ans2=[]
for item in l_num:
ans2=Insertsort2(item,ans2)
# print(item," ",ans2)
print(ans2)
#还有快速排序,堆排序
#https://blog.csdn.net/u013178472/article/details/54926531