Python课堂5--排序算法-冒泡排序

冒泡排序

1.冒泡排序(简单)

a = [5,8,9,3,2]
for i in range(len(a)-1):
    for j in range(i+1,len(a)):
        if a[i] > a[j]:
            temp = a[i]#定义临时变量存储a[i]
            a[i] = a[j]
            a[j] = temp
            del temp
print(a)

用函数方法实现:

def jdmp(list):
    for i in range(len(list)-1):
        for j in range(i+1,len(list)):
            if list[i] > list[j]:#list[i]为前一个数,list[j]为后一个数
                temp = list[i]
                list[i] = list[j]
                list[j] = temp
                del temp
    print(list)
a = [5,8,6,3,2]
jdmp(a)

2.冒泡排序(常规)

a = [5,8,9,3,2]
for i in range(len(a)-1):
    for j in range(len(a)-1-i):
        if a[j]>a[j+1]:
            temp = a[j]
            a[j] = a[j+1]
            a[j+1] = temp
            del temp
print(a)

用函数方法实现:

def cgmp(list):
    for i in range(len(list)-1):
        for j in range(len(list)-1-i):
            if list[j] > list[j+1]:
                temp = list[j]
                list[j] = list[j+1]
                list[j+1] = temp
                del temp
    print(list)
a = [5,8,9,3,2]
cgmp(a)

3.改进冒泡

a = [1,2,3,4,5,6,8,9,7]
for i in range(len(a)-1):
    flag = False
    for j in range(len(a)-1-i):
        if a[j]>a[j+1]:
            temp = a[j]
            a[j] = a[j+1]
            a[j+1] = temp
            del temp
            flag = True
    if not flag:#如果flag是不正确
        break
print(a)

用函数方法实现:

def gjmp(list):
    for i in range(len(list)-1):
        flag = False
        for j in range(len(list)-1-i):
            if a[j]>a[j+1]:
                temp = a[j]
                a[j] = a[j+1]
                a[j+1] = temp
                del temp
                flag = True
        if not flag:#如果flag是不正确
            break
    print(a)
a = [1,2,3,4,5,6,8,9,7]
gjmp(a)

不明白函数方法的在后面的课程有讲到,Python课堂8&9。

猜你喜欢

转载自blog.csdn.net/weixin_44362227/article/details/86509460