• 冒泡排序


    冒泡排序

    原理

    冒泡排序多次遍历列表。他比较相邻的元素,将不合顺序的交换。每一轮遍历都将下一个最大值放大正确的位置上。本质上,每个元素通过“冒泡”找打自己所属的位置。

    代码实现

    #!usr/bin/env python
    #-*- coding:utf-8 _*-
    # __author__:lianhaifeng
    # __time__:2020/8/12 23:41
    
    def bubbleSort(alist):
        exchanges = True
        passnum = len(alist) - 1
        while passnum > 0 and exchanges:
            exchanges = False
            for i in range(passnum):
                if alist[i] > alist[i+1]:
                    exchanges = True
                    temp = alist[i]
                    alist[i] = alist[i+1]
                    alist[i+1] = temp
            passnum -= 1
    
            
    def bubbleSort2(alist):
        passnum = len(alist) - 1
        for i in range(passnum, -1, -1):
            for j in range(i):
                if alist[j] > alist[j+1]:
                    alist[j], alist[j+1] = alist[j+1], alist[j]
    
    
    if __name__ == '__main__':
        alist = [8, 38, 65, 97, 76, 13, 27, 49]
        bubbleSort(alist)
        print(alist)
        alist = [8, 38, 65, 97, 76, 13, 27, 49]
        bubbleSort2(alist)
        print(alist)
  • 相关阅读:
    0523注册审核
    0520三级联动
    0519考试练习题
    0516ajax
    mysql 高级查询
    mysql
    HTML的格局与布局
    css样式表
    HTML表单
    HTML
  • 原文地址:https://www.cnblogs.com/lianhaifeng/p/13493866.html
Copyright © 2020-2023  润新知