欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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)

相关标签: python 冒泡排序