首页 > 编程语言 > 详细

python冒泡排序实现

时间:2019-10-14 15:55:52      阅读:75      评论:0      收藏:0      [点我收藏+]
代码:
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]

python冒泡排序实现

原文:https://www.cnblogs.com/sunflowers-lanqijiu/p/11671330.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!