• python--冒泡法


    # 4.冒泡法

    # 基础的
    lst = [9, 2, 32, 88, 32, 0, 12, 3]
    length = len(lst) # 8
    for i in range(length): # 0-7

    for j in range(length - i - 1):
    if lst[j] > lst[j + 1]:
    tmp = lst[j]
    lst[j] = lst[j + 1]
    lst[j + 1] = tmp
    print(lst)
    # [0, 2, 3, 9, 12, 32, 32, 88]

    # 优化的
    num_list = [
    [1, 9, 8, 5, 6, 7, 4, 3, 2],
    [1, 2, 3, 4, 5, 6, 7, 8, 9],
    [1, 2, 3, 4, 5, 6, 7, 9, 8]
    ]
    nums = num_list[0]
    print(nums)
    length = len(nums)
    count_swap = 0
    count = 0
    for i in range(length):
    flag = False
    for j in range(length - i - 1):
    count += 1
    if nums[j] > nums[j + 1]:
    tmp = nums[j]
    nums[j] = nums[j + 1]
    nums[j + 1] = tmp
    flag = True
    count_swap += 1
    if not flag:
    break
    print(nums, count_swap, count)
    # [1, 9, 8, 5, 6, 7, 4, 3, 2]
    # [1, 2, 3, 4, 5, 6, 7, 8, 9] 25 36

    # 使用冒泡算法进行从大到小的顺序排序
    num_list = [99, 12, 33, 0, 22, 11, 3, 234, 1]
    length = len(num_list)

    for i in range(length):
    flag = False
    for j in range(length - i - 1):
    if num_list[j] > num_list[j +1]:
    num_list[j], num_list[j+1] = num_list[j + 1], num_list[j]
    flag = True
    if not flag:
    break
    print(num_list)

    # [0, 1, 3, 11, 12, 22, 33, 99, 234]

    我的目标是每天厉害一点点
  • 相关阅读:
    页面与服务器的交互,,经典案例
    setInterval和clearInterval
    setAttribute,,,getAttribute,,,,
    字符串拼接
    上下图片连动效果
    文本框获得焦点
    获取机器上的时间
    检测奇偶性
    置顶博文
    P1962 斐波那契数列 题解
  • 原文地址:https://www.cnblogs.com/sidaofeng/p/10255974.html
Copyright © 2020-2023  润新知