print("\n合并排序法的最终结果为:",end=" ")
for i in range(len(list1)+len(list2)-2):
print("%d" %list3[i],end=" ")
def select_sort(data,size):
for base in range(size-1):
small = base
for j in range(base+1,size):
if data[j]<data[small]:
small = j
data[small],data[base] = data[base],data[small]
def My_Merge(size1,size2):
global list1
global list2
global list3
index1 = 0
index2 = 0
for index3 in range(len(list1)+len(list2)-2):
if list1[index1]<list2[index2]: # 比较两个数列,其中数小的先存储到合并后的数列中
list3.append(list1[index1])
index1+=1
print("此数字%d取自于第1个数列" %list3[index3])
else:
list3.append(list2[index2])
index2+=1
print("此数字%d取自于第2个数列" %list3[index3])
print("目前的合并排序结果为:",end=" ")
for i in range(index3+1):
print(list3[i]," ",end=" ")
print("\n")
七.快速排序法
1.过程简介
快速排序又称分割交换排序法,是目前公认最佳的排序法,也是使用"分而治之"(Divide and Conquer)的方式,先在数据中找到一个虚拟的中间值,并按此中间值将所有打算排序的数据分为两部分。其中,小于中间值的数据放在左边,大于中间值的数据放在右边,再以同样的方式分别处理左,右两边的数据,直到排序完成为止。
def inputarr(data,size):
for i in range(size):
data[i] = random.randint(1,100)
def showdata(data,size):
for i in range(size):
print("%3d" %data[i],end=" ")
print()
def quick(d,size,lf,rg):
# 第一项键值为d[lf]
if lf<rg:
lf_idx = lf+1
while d[lf_idx]<d[lf]:
if lf_idx+1 >size:
break
lf_idx+=1
rg_idx = rg
while d[rg_idx]>d[lf]:
rg_idx-=1
while lf_idx<rg_idx:
d[lf_idx],d[rg_idx] = d[rg_idx],d[lf_idx]
lf_idx+=1
while d[lf_idx]<d[lf]:
lf_idx+=1
rg_idx-=1
while d[rg_idx]>d[lf]:
rg_idx-=1
d[lf],d[rg_idx] = d[rg_idx],d[lf]
for i in range(size):
print("%3d" %d[i],end=" ")
print()
def inputarr(data,size):
for i in range(size):
data[i] = random.randint(0,999)
def showdata(data,size):
for i in range(size):
print("%3d" %data[i],end=" ")
print()
def radix(data,size):
n = 1 # n为基数,从个位数开始排序
while n<=100:
temp = [[0]*100 for row in range(10)]
for i in range(size):
m = (data[i]//n)%10
temp[m][i]=data[i]
k=0
for i in range(10):
for j in range(size):
if temp[i][j]!=0:
data[k] = temp[i][j]
k+=1
print("经过%3d位数排序后:" %n,end=" ")
showdata(data,size)
n=10*n