python排序算法(基础篇)冒泡排序

built-in 排序函数

	array = [8, 2, 6, 4, 5]
	sorted(array)  # [2, 4, 5, 6, 8]

冒泡排序

def bubble_sort(array):
    n = len(array)

    for i in range(n):
        # Create a flag that will allow the function to
        # terminate early if there's nothing left to sort
        already_sorted = True

        # Start looking at each item of the list one by one,
        # comparing it with its adjacent value. With each
        # iteration, the portion of the array that you look at
        # shrinks because the remaining items have already been
        # sorted.
        for j in range(n - i - 1):
            if array[j] > array[j + 1]:
                # If the item you're looking at is greater than its
                # adjacent value, then swap them
                array[j], array[j + 1] = array[j + 1], array[j]

                # Since you had to swap two elements,
                # set the `already_sorted` flag to `False` so the
                # algorithm doesn't finish prematurely
                already_sorted = False

        # If there were no swaps during the last iteration,
        # the array is already sorted, and you can terminate
        if already_sorted:
            break

    return array

在这里插入图片描述

现在一步一步去看此排序算法程序做了什么

  1. 代码开始时比较第一个元素【8】和它相邻的元素【2】从【8】>【2】值进行交换 结果是[2, 8, 6, 4, 5].
  2. 算法之后比较第二个元素【8】和相邻的元素【6】从【8】>【6】值交换 结果为[2, 6, 8, 4, 5].
  3. 之后以此类推
  4. 最终 算法比较到这 [2, 6, 4, 5, 8].时 算法完成了第一步遍历数组(i=0)
  5. 第二步(i=1) 列表的最后一个元素已经就位 接下来注意力集中在剩下四个元素身上 [2, 6, 4, 5] 在这一步的最后值6已经找到了他的位置第三步就是5 以此类推
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值