python 实现冒泡排序
程序员文章站
2022-03-24 15:44:02
...
用python实现冒泡排序
# 1.按元素长度升序排列
def maopao1(strs):
"""
:type strs: List[str]
"""
for i in range(len(strs)-1):
for j in range(i+1, len(strs)):
if len(strs[i]) > len(strs[j]):
(strs[i], strs[j]) = (strs[j], strs[i])
"""
temp = strs[i]
strs[i] = strs[j]
strs[j] = temp
"""
return strs
ret1 = maopao1(["file", "newfile", "file_name", "fl", "", "1"])
print(ret1)
# 2.按元素数值大小升序排列
def maopao2(strs):
"""
:type strs: List[str]
列表中存储数字
"""
for i in range(len(strs)-1):
for j in range(i+1, len(strs)):
if strs[i] > strs[j]:
(strs[i], strs[j]) = (strs[j], strs[i])
"""
temp = strs[i]
strs[i] = strs[j]
strs[j] = temp
"""
return strs
ret2 = maopao2([3, 2, 55, 111, 0, 1])
print(ret2)