输入数据(假定对十个数进行排序):
L=[]
for i in range(10):
a=int(input('please write a number:'))
L.append(a)
print (L)
一、冒泡排序
for i in range(10):
flag=1
for j in range(10,i,-1):
if L[j-1]>L[j]:
a=L[j-1]
L[j-1]=L[j]
L[j]=a
flag=0
if flag==1:
break
print (L)
二、选择排序
for i in range(10):
min=i
for j in range(i,10):
if L[min]>L[j]:
a=L[j]
L[j]=L[min]
L[min]=a
L[i]=L[min]
print(L)
三、直接插入排序
for i in range(1,10):
j=i
while j > 0 and L[j]<L[j-1]:
a=L[j]
L[j]=L[j-1]
L[j-1]=a
j=j-1
print(L)
四、快速排序
def fenzhi(array,low,high):
key= array[low]
for j in range(low+1,high+1):
if array[j]>=key:
pass
else:
array[low]=array[j]
low+=1
array[j]=array[low]
array[low]=key
return low
def quicksort(array,low,high):
if low<high:
temp=fenzhi(array,low,high)
quicksort(array,low,temp)
quicksort(array,temp+1,high)
if __name__ == '__main__':
array = [8, 10, 9, 6, 4, 16, 5, 13, 26, 18, 2, 45, 34, 23, 1, 7, 3]
print(array)
quicksort(array, 0, len(array) - 1)
print(array)