冒泡排序
data=[16,25,39,27,12,8,45,63]
print('冒泡排序法:原始数据为:')
for i in range(8):
print('%3d' %data[i],end='')
print()
for i in range(7,-1,-1):
for j in range(i):
if data[j]>data[j+1]:
data[j],data[j+1]=data[j+1],data[j]
print('排序后的结果为:')
for j in range(8):
print('%3d' %data[j],end='')
print()
选择排序
def showdata (data):
for i in range(8):
print('%3d' %data[i],end='')
print()
def select (data):
for i in range(7):
for j in range(i+1,8):
if data[i]>data[j]:
data[i],data[j]=data[j],data[i]
data=[16,25,39,27,12,8,45,63]
print('原始数据为:')
showdata(data)
print('\n-------------------------------------')
select(data)
print("排序后的数据为:")
showdata(data)
快速排序
import random
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):
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()
quick(d, size, lf, rg_idx - 1)
quick(d, size, rg_idx + 1, rg)
def main():
data = [0] * 100
size = int(input('请输入数列的大小(100以下):'))
inputarr(data, size)
print('您输入的原始数据是:')
showdata(data, size)
print('排序的过程如下:')
quick(data, size, 0, size - 1)
print('最终的排序结果为:')
showdata(data, size)
main()
基数排序
import random
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('%5d' %data[i],end='')
print()
def radix(data,size):
n=1
while n<=100:
tmp=[[0]*100 for row in range(10)]
for i in range(size):
m=(data[i]//n)%10
tmp[m][i]=data[i]
k=0
for i in range(10):
for j in range(size):
if tmp[i][j] != 0:
data[k]=tmp[i][j]
k+=1
print('经过%3d位数排序后:' %n,end='')
showdata(data,size)
n=10*n
def main():
data=[0]*100
size=int(input('请输入数列的大小(100以下):'))
print('您输入的原始数据是:')
inputarr (data,size)
showdata (data,size)
radix (data,size)
main()