python冒泡排序实现
代码:
list=[3,51,4,8,0,2,47]
n=len(list)
for i in range(0,n-1):
for j in range(0,n-1-i):
if list[j]>list[j+1]:
arry=list[j+1]
list[j+1]=list[j]
list[j]=arry
print(list)
结果:
[0, 2, 3, 4, 8, 47, 51]
代码:
from random import randrange, shuffle
def Bubblesort():
array=[]
while len(array)<12:
array.append(randrange(-99,101,3))
shuffle(array)
print("排序前的数组:{}".format(array))
for i in range(12):
for j in range(0,12-1-i):
if array[j]>array[j+1]:
buf=array[j+1]
array[j+1]=array[j]
array[j]=buf
print("排序后的数组:{}".format(array))
Bubblesort()
结果:
排序前的数组:[-54, 0, -24, -24, -18, 33, 90, -36, 93, 21, -90, -48]
排序后的数组:[-90, -54, -48, -36, -24, -24, -18, 0, 21, 33, 90, 93]
代码:
def Bubblesort(arr,oder):
max=len(arr)
for i in range(0,max):
j=1
while(j<max-i):
if((arr[j-1]>arr[j]and int(oder)>0)or (arr[j-1]<arr[j]and int(oder)<0)):
arr[j-1],arr[j]=arr[j],arr[j-1]
j+=1
i+=1
return arr
A = [64, 25, 12, 22, 11]
print(Bubblesort(A, -1))
print(Bubblesort(A, 1))
结果:
[64, 25, 22, 12, 11]
[11, 12, 22, 25, 64]
如有不对之处,请多多读指教