冒泡排序(以Python实现)

目录

1. while实现冒泡排序

def bubble_sort_while(a_list):
    """冒泡排序 while版本"""
    num = len(a_list)
    j = 0
    while j < num-1:
        i = 0
        count = 0;
        while i < num-1-j:
            if a_list[i] > a_list[i+1]:
                a_list[i],a_list[i+1] = a_list[i+1], a_list[i]
                count += 1
            i += 1
        # 优化冒泡排序,对于有序列表
        if count == 0:
            break
        j += 1

    return a_list

2. for实现冒泡排序

def bubble_sort_for(b_list):
    """冒泡排序 for版本"""
    num = len(b_list)
    for j in range(0, num-1):
        count = 0
        for i in range(0, num-1-j):
            if b_list[i] > b_list[i+1]:
                b_list[i],b_list[i+1] = b_list[i+1], b_list[i]
                count += 1
        # 优化冒泡排序,对于有序列表
        if count == 0:
            break
    return b_list

3. 测试用例

if __name__ == '__main__':
    a_list = [2,1,4,8,9,6]
    print(bubble_sort_while(a_list))
    b_list = [8,1,5,9,10,20]
    print(bubble_sort_for(b_list))

猜你喜欢

转载自www.cnblogs.com/yueyun00/p/10282122.html
今日推荐