Python's title bubbling algorithmic problems
Bubble algorithm in Python, which is defined by the means for loop, the list is sorted by specific rules, wherein the rules generally refers twenty-two compared by size reorder the list, then, directly following the code directly to code explain the principles within them.
在这里插入代码片
lst=[2,4,6,66,22,4,8,93,2,0]
length=len(lst)
count_swap=0
count=0
for i in range(length):
count+=1#冒泡循环的次数
#count可以理解为一个计数器,记录循环的次数,一般等于
#列表的长度
for j in range(length-1-i):
#外循环为0时,内循环取列表倒数第二个元素
if lst[j] > lst[j + 1]:
#此时列表的倒数二个数和列表的倒数第一个数开始比较,
#在此例子中也就是比较2和0,
count_swap+=1#冒泡循环数字交换的次数
lst[j],lst[j+1]=lst[j+1],lst[j]
#上述为真,也就是2》0,那么将2和0的位置互换
#通过内外两层循环直到列表从右到左循环完毕。,
print(lst)
print(count_swap)#内循环次数
print(count)#外循环次数
print(length)#字符串列表的长度
lst_1=set(lst)#list转换成一个set集合,去除重复内容,但次序是#打乱的