冒泡排序及改进—Python实现
程序员文章站
2024-03-22 13:34:40
...
冒泡排序
冒泡排序的算法思路在于对无序表进行多趟比较交换,每趟包括了两次两两相邻比较,并将逆序的数据项交换位置,最终能将本趟的最大项就位,经过n-1趟比较,实现整表排序。图表展示
代码
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp=alist[i]
alist[i]=alist[i+1]
alist[i+1]=temp
alist=[52,312,54,7,3,2,56,34,65]
bubbleSort(alist)
print(alist)
性能改进
如果某趟比对没有发生任何交换,说明列表已经排好序,可以提前结束算法
def shortBubbleSort(alist):
exchanges=True
passnum=len(alist)-1
while passnum >0 and exchanges:
exchanges=False
for i in range(passnum):
if alist[i]>alist[i+1]:
exchanges=True
temp=alist[i]
alist[i]=alist[i+1]
alist[i+1]=temp
passnum-=1
alist=[52,312,54,7,3,2,56,34,65]
shortBubbleSort(alist)
print(alist)